def plot_categ_spatial(mod, adata, sample_col, color, n_columns=2, figure_size=(24, 5.7), point_size=0.8, text_size=9): for_plot = adata.obs[["imagecol", "imagerow", sample_col]] for_plot["color"] = color # fix types for_plot["color"] = pd.Categorical(for_plot["color"], ordered=True) # for_plot['color'] = pd.to_numeric(for_plot['color']) for_plot["sample"] = pd.Categorical(for_plot[sample_col], ordered=False) for_plot["imagecol"] = pd.to_numeric(for_plot["imagecol"]) for_plot["imagerow"] = -pd.to_numeric(for_plot["imagerow"]) ax = ( plotnine.ggplot( for_plot, plotnine.aes(x="imagecol", y="imagerow", color="color")) + plotnine.geom_point(size=point_size) # + plotnine.scale_color_cmap() + plotnine.coord_fixed() + plotnine.theme_bw() + plotnine.theme( panel_background=plotnine.element_rect( fill="black", colour="black", size=0, linetype="solid"), panel_grid_major=plotnine.element_line( size=0, linetype="solid", colour="black"), panel_grid_minor=plotnine.element_line( size=0, linetype="solid", colour="black"), strip_text=plotnine.element_text(size=text_size), ) + plotnine.facet_wrap("~sample", ncol=n_columns) + plotnine.theme(figure_size=figure_size)) return ax
def test_annotation_logticks_coord_flip(): p = (ggplot(df, aes('x', 'x')) + annotation_logticks(sides='b', size=.75) + geom_point() + scale_x_log10() + scale_y_log10() + coord_flip() + theme(panel_grid_minor=element_line(color='green'), panel_grid_major=element_line(color='red'))) assert p == 'annotation_logticks_coord_flip'
def cell_cycle_phase_barplot(adata, palette='Set2'): """Plots the proportion of cells in each phase of the cell cycle See also: cell_cycle_phase_pieplot for the matplotlib pie chart Parameters ----------- adata: AnnData The AnnData object being used for the analysis. Must be previously evaluated by `tl.annotate_cell_cycle`. Returns ----------- A plotnine barplot with the total counts of cell in each phase of the cell cycle. """ plt_data = adata.obs.copy() plt_data['cell_cycle_phase'] = pd.Categorical( plt_data['cell_cycle_phase'], categories=['G1 post-mitotic', 'G1 pre-replication', 'S/G2/M']) cycle_plot = ( ggplot(plt_data, aes('cell_cycle_phase', fill='cell_cycle_phase')) + geom_bar() + coord_flip() + guides(fill=False) + labs(y='', x='Cell cycle phase') + theme_light() + theme(panel_grid_major_y=element_blank(), panel_grid_minor_y=element_blank(), panel_grid_major_x=element_line(size=1.5), panel_grid_minor_x=element_line(size=1.5)) + scale_fill_brewer(type='qual', palette=palette)) return cycle_plot
def test_annotation_logticks(): # The grid should align with the logticks p = (ggplot(df, aes('x', 'x')) + annotation_logticks(sides='b', size=.75) + geom_point() + scale_x_log10() + scale_y_log10() + theme(panel_grid_minor=element_line(color='green'), panel_grid_major=element_line(color='red'))) assert p == 'annotation_logticks'
def test_annotation_logticks_coord_flip_discrete_bottom(): df2 = df.assign(discrete=pd.Categorical(['A' + str(a) for a in df['x']])) p = (ggplot(df2, aes('x', 'discrete')) + annotation_logticks(sides='b', size=.75) + geom_point() + scale_x_log10() + coord_flip() + theme(panel_grid_minor=element_line(color='green'), panel_grid_major=element_line(color='red'))) assert p == 'annotation_logticks_coord_flip_discrete_bottom'
def test_annotation_logticks_base_8(): base = 8 df = pd.DataFrame({'x': base**np.arange(4)}) # The grid should align with the logticks p = (ggplot(df, aes('x', 'x')) + annotation_logticks(sides='b', size=.75) + geom_point() + scale_x_continuous(trans=log_trans(base=base)) + theme(panel_grid_minor=element_line(color='green'), panel_grid_major=element_line(color='red'))) assert p == 'annotation_logticks_base_8'
def bandit_learning_format(plot: gg.ggplot) -> gg.ggplot: """Add nice bandit formatting to ggplot.""" plot += gg.scale_y_continuous(breaks=np.arange(0, 1.1, 0.1).tolist()) plot += gg.theme(panel_grid_major_y=gg.element_line(size=2.5), panel_grid_minor_y=gg.element_line(size=0)) plot += gg.geom_hline(gg.aes(yintercept=BASE_REGRET), linetype='dashed', alpha=0.4, size=1.75) plot += gg.coord_cartesian(ylim=(0, 1)) return plot
def test_annotation_logticks_faceting(): n = len(df) df2 = pd.DataFrame({ 'x': np.hstack([df['x'], df['x']]), 'g': list('a' * n + 'b' * n) }) p = (ggplot(df2) + annotation_logticks(sides='b', size=.75) + geom_point(aes('x', 'x')) + scale_x_log10() + scale_y_log10() + facet_wrap('g') + theme(panel_grid_minor=element_line(color='green'), panel_grid_major=element_line(color='red'))) assert p == 'annotation_logticks_faceting'
def plot_fitting(x, y, resonance_frequency, parameter): """ Plots the phase response and the corresponding fit of the harmonic damped oscillator. Args: x (`float array`): X coordinates (frequency in kHz) y (`float array`): Y coordinates (phase in radians) resonance_frequency (`float array`): Resonance frequency given by the fit of x and y parameter (`float array`): Others parameters of function fit (Q factor, offset, linear background) Returns: p (`ggplot object`): Returns a ggplot object """ y_fit = fit_function(x, resonance_frequency, parameter[0], parameter[1], parameter[2]) y_fit.name = 'Phase fit' x.name = 'Frequency (kHz)' y.name = 'Phase (rad)' data = concat([x, y, y_fit], axis=1) col_names = list(data) # Plot data p = ggplot(aes(x=col_names[0], y=col_names[1]), data=data) + \ geom_point() + \ geom_line(aes(x=col_names[0], y=col_names[2]), color='red', size=0.5) + \ theme_seaborn(style='ticks', context='talk', font_scale=0.75) + \ theme(figure_size=(15, 7), strip_background=element_rect(fill='white'), axis_line_x=element_line(color='black'), axis_line_y=element_line(color='black'), legend_key=element_rect(fill='white', color='white')) return p
def theme_cognoma(fontsize_mult=1): return (gg.theme_bw(base_size=14 * fontsize_mult) + gg.theme( line=gg.element_line(color="#4d4d4d"), rect=gg.element_rect(fill="white", color=None), text=gg.element_text(color="black"), axis_ticks=gg.element_line(color="#4d4d4d"), legend_key=gg.element_rect(color=None), panel_border=gg.element_rect(color="#4d4d4d"), panel_grid=gg.element_line(color="#b3b3b3"), panel_grid_major_x=gg.element_blank(), panel_grid_minor=gg.element_blank(), strip_background=gg.element_rect(fill="#FEF2E2", color="#4d4d4d"), axis_text=gg.element_text(size=12 * fontsize_mult, color="#4d4d4d"), axis_title_x=gg.element_text(size=13 * fontsize_mult, color="#4d4d4d"), axis_title_y=gg.element_text(size=13 * fontsize_mult, color="#4d4d4d")))
def plot_downstream(clwe, table, output, ylim): df = pd.read_csv(data_file(table)) df = df[df.clwe == clwe] df = df.assign( refine=pd.Categorical(df['refine'], ['Original', '+retrofit', '+synthetic']), language=pd.Categorical(df['language'], ['DE', 'ES', 'FR', 'IT', 'JA', 'RU', 'ZH', 'AVG']) ) g = p9.ggplot(df, p9.aes(x='language', y='accuracy', fill='refine')) g += p9.geom_bar(position='dodge', stat='identity', width=.8) g += p9.coord_cartesian(ylim=ylim) g += p9.scale_fill_manual(['#999999', '#EA5F94', '#FFB14E']) g += p9.theme_void(base_size=FONT_SIZE, base_family='Arial') g += p9.theme( plot_background=p9.element_rect(fill='white'), panel_grid_major_y=p9.element_line(), axis_text_x=p9.element_text(margin={'t': 10}), axis_text_y=p9.element_text(margin={'r': 8}), legend_position=(.7, .9), legend_direction='horizontal', legend_title=p9.element_blank(), legend_text=p9.element_text(size=FONT_SIZE), legend_box_margin=0, figure_size=(12, 3) ) g.save(filename=output_file(output))
def mpl_theme(width=12, height=8): return [ pn.theme_matplotlib(), pn.theme(figure_size=(width, height), strip_background=pn.element_rect(color='w', fill='w'), panel_grid=pn.element_line(color='k', alpha=.1)) ]
def scatter_plot(df, xcol, ycol, domain, xname=None, yname=None, log=False, width=6, height=6, clamp=True, tickCount=5): assert len(domain) == 2 POINT_SIZE = 0.5 DASH_PATTERN = (0, (3, 1)) if xname == None: xname = xcol if yname == None: yname = ycol # formater for axes' labels ax_formatter = mizani.custom_format('{:n}') if clamp: # clamp overflowing values if required df = df.copy(deep=True) df.loc[df[xcol] > domain[1], xcol] = domain[1] df.loc[df[ycol] > domain[1], ycol] = domain[1] # generate scatter plot scatter = p9.ggplot(df) scatter += p9.aes(x=xcol, y=ycol) scatter += p9.geom_point(size=POINT_SIZE, na_rm=True) scatter += p9.labs(x=xname, y=yname) if log: # log scale scatter += p9.scale_x_log10(limits=domain, labels=ax_formatter) scatter += p9.scale_y_log10(limits=domain, labels=ax_formatter) else: scatter += p9.scale_x_continuous(limits=domain, labels=ax_formatter) scatter += p9.scale_y_continuous(limits=domain, labels=ax_formatter) #scatter += p9.theme_xkcd() scatter += p9.theme_bw() scatter += p9.theme( panel_grid_major=p9.element_line(color='#666666', alpha=0.5)) scatter += p9.theme(figure_size=(width, height)) # generate additional lines scatter += p9.geom_abline(intercept=0, slope=1, linetype=DASH_PATTERN) # diagonal scatter += p9.geom_vline(xintercept=domain[1], linetype=DASH_PATTERN) # vertical rule scatter += p9.geom_hline(yintercept=domain[1], linetype=DASH_PATTERN) # horizontal rule res = scatter return res
def __init__(self, args, display_title='Analysis'): super().__init__(args, display_title) fusion_pos_file = Mkref_fusion.parse_genomeDir( args.fusion_genomeDir)['fusion_pos'] self.pos_dict = Count_fusion.read_pos_file(fusion_pos_file) self.p9_theme = { 'axis_line_x': p9.element_line(size=2, colour="black"), 'axis_line_y': p9.element_line(size=2, colour="black"), 'panel_grid_major': p9.element_blank(), 'panel_grid_minor': p9.element_blank(), 'panel_border': p9.element_blank(), 'panel_background': p9.element_blank(), 'axis_text_x': p9.element_text(colour="black"), 'axis_text_y': p9.element_text(colour="black"), }
def plot_average(df: pd.DataFrame, sweep_vars: Sequence[Text] = None, group_col: Text = 'noise_scale') -> gg.ggplot: """Plots the average regret through time by noise_scale.""" p = plotting.plot_regret_average( df_in=df, group_col=group_col, episode=sweep.NUM_EPISODES, sweep_vars=sweep_vars ) p += gg.scale_y_continuous(breaks=np.arange(0, 1.1, 0.1).tolist()) p += gg.theme(panel_grid_major_y=gg.element_line(size=2.5), panel_grid_minor_y=gg.element_line(size=0),) p += gg.geom_hline(gg.aes(yintercept=bandit_analysis.BASE_REGRET), linetype='dashed', alpha=0.4, size=1.75) p += gg.coord_cartesian(ylim=(0, 1)) return p
def scatter_plot2(df1, df2, xcol, ycol, domain, color1='black', color2='red', xname=None, yname=None, log=False, width=6, height=6, clamp=True, tickCount=5): assert len(domain) == 2 POINT_SIZE = 1.5 DASH_PATTERN = (0, (6, 2)) if xname is None: xname = xcol if yname is None: yname = ycol # formatter for axes' labels ax_formatter = mizani.custom_format('{:n}') if clamp: # clamp overflowing values if required df1 = df1.copy(deep=True) df1.loc[df1[xcol] > domain[1], xcol] = domain[1] df1.loc[df1[ycol] > domain[1], ycol] = domain[1] df2 = df2.copy(deep=True) df2.loc[df2[xcol] > domain[1], xcol] = domain[1] df2.loc[df2[ycol] > domain[1], ycol] = domain[1] # generate scatter plot scatter = p9.ggplot(df1) scatter += p9.aes(x=xcol, y=ycol) scatter += p9.geom_point(size=POINT_SIZE, na_rm=True, color=color1, alpha=0.5) scatter += p9.geom_point(size=POINT_SIZE, na_rm=True, data=df2, color=color2, alpha=0.5) scatter += p9.labs(x=xname, y=yname) # rug plots scatter += p9.geom_rug(na_rm=True, sides="tr", color=color1, alpha=0.05) scatter += p9.geom_rug(na_rm=True, sides="tr", data=df2, color=color2, alpha=0.05) if log: # log scale scatter += p9.scale_x_log10(limits=domain, labels=ax_formatter) scatter += p9.scale_y_log10(limits=domain, labels=ax_formatter) else: scatter += p9.scale_x_continuous(limits=domain, labels=ax_formatter) scatter += p9.scale_y_continuous(limits=domain, labels=ax_formatter) # scatter += p9.theme_xkcd() scatter += p9.theme_bw() scatter += p9.theme(panel_grid_major=p9.element_line(color='#666666', alpha=0.5)) scatter += p9.theme(panel_grid_minor=p9.element_blank()) scatter += p9.theme(figure_size=(width, height)) scatter += p9.theme(text=p9.element_text(size=24, color="black")) # generate additional lines scatter += p9.geom_abline(intercept=0, slope=1, linetype=DASH_PATTERN) # diagonal scatter += p9.geom_vline(xintercept=domain[1], linetype=DASH_PATTERN) # vertical rule scatter += p9.geom_hline(yintercept=domain[1], linetype=DASH_PATTERN) # horizontal rule res = scatter return res
def theme_cognoma(fontsize_mult=1): import plotnine as gg return (gg.theme_bw(base_size = 14 * fontsize_mult) + gg.theme( line = gg.element_line(color = "#4d4d4d"), rect = gg.element_rect(fill = "white", color = None), text = gg.element_text(color = "black"), axis_ticks = gg.element_line(color = "#4d4d4d"), legend_key = gg.element_rect(color = None), panel_border = gg.element_rect(color = "#4d4d4d"), panel_grid = gg.element_line(color = "#b3b3b3"), panel_grid_major_x = gg.element_blank(), panel_grid_minor = gg.element_blank(), strip_background = gg.element_rect(fill = "#FEF2E2", color = "#4d4d4d"), axis_text = gg.element_text(size = 12 * fontsize_mult, color="#4d4d4d"), axis_title_x = gg.element_text(size = 13 * fontsize_mult, color="#4d4d4d"), axis_title_y = gg.element_text(size = 13 * fontsize_mult, color="#4d4d4d") ))
def plot_response_shift(x, y, resonance_frequency_without, parameter_without, xx, yy, resonance_frequency_with, parameter): """ Plots the phase response of pre start data without and with cell attached to cantilever with the respective function fit. Args: x (`float array`): X coordinates w/o cell (frequency in kHz) y (`float array`): Y coordinates w/o cell (phase in radians) xx (`float array`): X coordinates w/ cell(frequency in kHz) yy (`float array`): Y coordinates w/ cell (phase in radians) resonance_frequency_without (`float array`): Resonance frequency given by the fit of x and y w/o cell resonance_frequency_with (`float array`): Resonance frequency given by the fit of x and y w/ cell parameter (`float array`): Others parameters of function fit (Q factor, offset, linear background) w/o cell parameter_without (`float array`): Others parameters of function fit (Q factor, offset, linear background) w/ cell Returns: p (`ggplot object`): Returns a ggplot object """ y_fit_without = fit_function(x, resonance_frequency_without, parameter_without[0], parameter_without[1], parameter_without[2]) y_fit_with = fit_function(xx, resonance_frequency_with, parameter[0], parameter[1], parameter[2]) y_fit_without.name = 'Phase fit w/o cell att.' y_fit_with.name = 'Phase fit w cell att.' x.name = 'Frequency without (kHz)' y.name = 'Raw phase w/o cell att.' xx.name = 'Frequency with (kHz)' yy.name = 'Raw phase w cell att.' data = concat([x, y, y_fit_without, xx, yy, y_fit_with], axis=1) df = melt(data, id_vars=['Frequency with (kHz)'], value_vars=['Phase fit w cell att.', 'Phase fit w/o cell att.']) df.loc[df['variable'] == 'Phase fit w/o cell att.', 'Frequency with (kHz)'] = x.values df2 = melt(data, id_vars=['Frequency with (kHz)'], value_vars=['Raw phase w cell att.', 'Raw phase w/o cell att.']) df2.loc[df2['variable'] == 'Raw phase w/o cell att.', 'Frequency with (kHz)'] = x.values # Plot data p = ggplot(data=df) + \ geom_point(aes(x="Frequency with (kHz)", y='value', fill='variable'), data=df2, alpha=0.6) + \ geom_line(aes(x="Frequency with (kHz)", y='value', color='variable')) + \ xlab('Frequency (kHz)') + \ ylab('Phase (rad)') + \ labs(fill='Raw data', color='Function fits') + \ theme_seaborn(style='ticks', context='talk', font_scale=0.75) + \ theme(figure_size=(15, 7), strip_background=element_rect(fill='white'), axis_line_x=element_line(color='black'), axis_line_y=element_line(color='black'), legend_key=element_rect(fill='white', color='white')) return p
def __init__(self, base_size=11, base_family='DejaVu Sans'): theme_light.__init__(self, base_size, base_family) self.add_theme(theme( axis_ticks=element_line(color='#DDDDDD', size=0.5), panel_border=element_rect(fill='None', color='#838383', size=1), strip_background=element_rect( fill='#DDDDDD', color='#838383', size=1), strip_text_x=element_text(color='black'), strip_text_y=element_text(color='black', angle=-90) ), inplace=True)
def theme_energinet() -> p9.themes.theme: """Create a simple Energinet theme.""" return p9.theme( text=p9.element_text(family=endktheme.style.font_family()), axis_line=p9.element_line(color="black"), plot_background=p9.element_blank(), panel_background=p9.element_rect(fill="white"), legend_background=p9.element_rect(fill="white"), legend_key=p9.element_blank(), panel_grid=p9.element_blank(), axis_ticks=p9.element_blank(), )
def __init__(self, base_size=11, base_family='DejaVu Sans'): theme_light.__init__(self, base_size, base_family) self.add_theme(theme( axis_ticks=element_line(color='#DDDDDD', size=0.5), panel_border=element_rect(fill='None', color='#838383', size=1), strip_background=element_rect( fill='#DDDDDD', color='#838383', size=1), strip_text_x=element_text(color='black'), strip_text_y=element_text(color='black', angle=-90), legend_key=element_blank() ), inplace=True)
def _plot_theme(grid_axis='both', grid_lines='both', theme='bw'): """Internal function provides consistent theme across plots. Currently a slightly modified version of theme_bw() with configurable grid lines. Args: grid_axis: controls the axis on which to draw grid lines - Accepts: None, 'x', 'y', 'both' - Default: 'both' grid_lines: controls whether major or minor grid lines are drawn - Accepts: None, 'major', 'minor', 'both' - Default: 'both' theme: - Accepts: 'bw', 'classic', 'gray', 'grey', 'seaborn', '538', 'dark', 'matplotlib', 'minimal', 'xkcd', 'light' - Default: 'bw' Returns: A theme object to be added to a plotnine.ggplot() object. """ import plotnine as gg assert (grid_axis in [None, 'x', 'y', 'both']) assert (grid_lines in [None, 'major', 'minor', 'both']) assert (theme in [ 'bw', 'classic', 'gray', 'grey', 'seaborn', '538', 'dark', 'matplotlib', 'minimal', 'xkcd', 'light' ]) drop_grid = set() if grid_axis is None or grid_lines is None: drop_grid.update(['panel_grid_major', 'panel_grid_minor']) elif grid_axis == 'x': drop_grid.update(['panel_grid_major_y', 'panel_grid_minor_y']) if grid_lines == 'major': drop_grid.add('panel_grid_minor_y') elif grid_lines == 'minor': drop_grid.add('panel_grid_major_y') elif grid_axis == 'y': drop_grid.update(['panel_grid_major_x', 'panel_grid_minor_x']) if grid_lines == 'major': drop_grid.add('panel_grid_minor_x') elif grid_lines == 'minor': drop_grid.add('panel_grid_major_x') grid_opt = dict() for x in drop_grid: grid_opt[x] = gg.element_blank() return getattr(gg, 'theme_'+theme)() + \ gg.theme(panel_border = gg.element_blank(), axis_line = gg.element_line(color = "black"), **grid_opt)
def test_add_complete_partial(): theme1 = theme_gray() theme2 = theme1 + theme(axis_line_x=element_line()) assert theme2 != theme1 assert theme2.themeables != theme1.themeables assert theme2.rcParams == theme1.rcParams # specific difference for name in theme2.themeables: if name == 'axis_line_x': assert theme2.themeables[name] != theme1.themeables[name] else: assert theme2.themeables[name] == theme1.themeables[name]
def test_add_complete_partial(): theme1 = theme_gray() theme2 = theme1 + theme(axis_line_x=element_line()) assert theme2 != theme1 assert theme2.themeables != theme1.themeables assert theme2.rcParams == theme1.rcParams # specific difference for name in theme2.themeables: if name == 'axis_line_x': assert theme2.themeables[name] != theme1.themeables[name] else: assert theme2.themeables[name] == theme1.themeables[name]
def __init__(self, base_size=11, base_family="DejaVu Sans"): theme_light.__init__(self, base_size, base_family) self.add_theme( theme( axis_ticks=element_line(color="#DDDDDD", size=0.5), panel_border=element_rect(fill="None", color="#838383", size=1), strip_background=element_rect(fill="#DDDDDD", color="#838383", size=1), strip_text_x=element_text(color="black"), strip_text_y=element_text(color="black", angle=-90), legend_key=element_blank(), ), inplace=True, )
def theme_tufte(base_size=11, base_family='serif', lines=True, ticks=True): """ Theme inspired by Chapter 6 'Data-Ink Maximization and Graphical Design` of Edward Tufte's 'The Visual Display of Quantitative Information`. Parameters ---------- base_size : int, optional Base font size. All text sizes are scaled versions of the base font size. Default is 11. base_family : str, optional Base font family. lines : bool, optional Draw axis spines. Default is True. ticks : bool, optional Draw axis ticks. Default is True. Returns ------- Plotnine theme. """ ret = (p9.theme_bw(base_size=base_size, base_family=base_family) + p9.theme(legend_background=p9.element_blank(), legend_key=p9.element_blank(), panel_background=p9.element_blank(), strip_background=p9.element_blank(), plot_background=p9.element_rect(fill='white'), axis_line=p9.element_line(size=0.5), axis_ticks=p9.element_line(size=0.5), panel_grid=p9.element_blank())) if not ticks: ret = ret + p9.theme(axis_ticks=p9.element_blank()) if not lines: ret = ret + p9.theme(axis_line=p9.element_blank()) return ret
def __init__(self, *args, **kwargs): """See main class docstring.""" p9.theme_matplotlib.__init__(self, *args, **kwargs) gray = '#D9D9D9' # gray used in themes.theme_matplotlib self.add_theme( p9.theme( panel_border=p9.element_rect(color=gray, size=0.7), axis_line=p9.element_blank(), axis_ticks_length=0, axis_ticks=p9.element_blank(), panel_grid_major=p9.element_line(color=gray, size=0.7), panel_grid_minor=p9.element_blank(), panel_ontop=True, # plot panel on top of grid ), inplace=True)
def test_add_empty_theme_element(): # An empty theme element does not alter the theme theme1 = theme_gray() + theme(axis_line_x=element_line(color='red')) theme2 = theme1 + theme(axis_line_x=element_line()) assert theme1 == theme2
def test_add_partial_complete(): theme1 = theme(axis_line_x=element_line()) theme2 = theme_gray() theme3 = theme1 + theme2 assert theme3 == theme2
def test_add_empty_theme_element(): # An empty theme element does not alter the theme theme1 = theme_gray() + theme(axis_line_x=element_line(color='red')) theme2 = theme1 + theme(axis_line_x=element_line()) assert theme1 == theme2
def test_add_partial_complete(): theme1 = theme(axis_line_x=element_line()) theme2 = theme_gray() theme3 = theme1 + theme2 assert theme3 == theme2
def test_add_partial_complete(): theme1 = theme(axis_line_x=element_line()) theme2 = theme_gray() theme3 = theme1 + theme2 assert theme3 == theme2 def test_add_empty_theme_element(): # An empty theme element does not alter the theme theme1 = theme_gray() + theme(axis_line_x=element_line(color='red')) theme2 = theme1 + theme(axis_line_x=element_line()) assert theme1 == theme2 l1 = element_line(color='red', size=1, linewidth=1, linetype='solid') l2 = element_line(color='blue', size=2, linewidth=2) l3 = element_line(color='blue', size=2, linewidth=2, linetype='solid') blank = element_blank() def test_add_element_heirarchy(): # parent themeable modifies child themeable theme1 = theme_gray() + theme(axis_line_x=l1) # child theme2 = theme1 + theme(axis_line=l2) # parent theme3 = theme1 + theme(axis_line_x=l3) # child, for comparison assert theme2.themeables['axis_line_x'] == \ theme3.themeables['axis_line_x'] theme1 = theme_gray() + theme(axis_line_x=l1) # child theme2 = theme1 + theme(line=l2) # grand-parent
def plot_factor_spatial( adata, fact, cluster_names, fact_ind=[0], trans="log", sample_name=None, samples_col="sample", obs_x="imagecol", obs_y="imagerow", n_columns=6, max_col=5000, col_breaks=[0.1, 100, 1000, 3000], figure_size=(24, 5.7), point_size=0.8, text_size=9, ): r"""Plot expression of factors / cell types in space. Convenient but not as powerful as scanpy plotting. :param adata: anndata object with spatial data :param fact: pd.DataFrame with spatial expression of factors (W), e.g. mod.spot_factors_df :param cluster_names: names of those factors to show on a plot :param fact_ind: index of factors to plot :param trans: transform colorscale? passed to plotnine.scale_color_cmap :param sample_name: if anndata object contains multiple samples specify which sample to plot (no warning given if not) :param samples_col: if anndata object contains multiple which .obs columns specifies sample? :param obs_x: which .obs columns specifies x coordinate? :param obs_y: which .obs columns specifies y coordinate? :param n_columns: how many factors / clusters to plot in each row (plotnine.facet_grid) :param max_col: colorscale maximum expression in fact :param col_breaks: colorscale breaks :param figure_size: figures size works weirdly (only x axis has an effect, use 24 for 6-column plot, 12 for 3, 8 for 2 ...). :param point_size: point size of spots :param text_size: text size """ if sample_name is not None: sample_ind = np.isin(adata.obs[samples_col], sample_name) else: sample_ind = np.repeat(True, adata.shape[0]) # adata.obsm['X_spatial'][:,0] vs adata.obs['imagecol'] & adata.obs['imagerow'] for_plot = np.concatenate( ( adata.obs[obs_x].values.reshape((adata.obs.shape[0], 1)), -adata.obs[obs_y].values.reshape((adata.obs.shape[0], 1)), fact.iloc[:, fact_ind[0]].values.reshape((adata.obs.shape[0], 1)), np.array([ cluster_names[fact_ind[0]] for j in range(adata.obs.shape[0]) ]).reshape((adata.obs.shape[0], 1)), ), 1, ) for_plot = pd.DataFrame( for_plot, index=adata.obs.index, columns=["imagecol", "imagerow", "weights", "cluster"]) # select only correct sample for_plot = for_plot.loc[sample_ind, :] for i in fact_ind[1:]: for_plot1 = np.concatenate( ( adata.obs[obs_x].values.reshape((adata.obs.shape[0], 1)), -adata.obs[obs_y].values.reshape((adata.obs.shape[0], 1)), fact.iloc[:, i].values.reshape((adata.obs.shape[0], 1)), np.array([cluster_names[i] for j in range(adata.obs.shape[0])]).reshape( (adata.obs.shape[0], 1)), ), 1, ) for_plot1 = pd.DataFrame( for_plot1, index=adata.obs.index, columns=["imagecol", "imagerow", "weights", "cluster"]) # select only correct sample for_plot1 = for_plot1.loc[sample_ind, :] for_plot = pd.concat((for_plot, for_plot1)) for_plot["imagecol"] = pd.to_numeric(for_plot["imagecol"]) for_plot["imagerow"] = pd.to_numeric(for_plot["imagerow"]) for_plot["weights"] = pd.to_numeric(for_plot["weights"]) for_plot["cluster"] = pd.Categorical(for_plot["cluster"], categories=cluster_names[fact_ind], ordered=True) # print(np.log(np.max(for_plot['weights']))) ax = (plotnine.ggplot( for_plot, plotnine.aes("imagecol", "imagerow", color="weights")) + plotnine.geom_point(size=point_size) + plotnine.scale_color_cmap("magma", trans=trans, limits=[0.1, max_col], breaks=col_breaks + [max_col]) + plotnine.coord_fixed() + plotnine.theme_bw() + plotnine.theme( panel_background=plotnine.element_rect( fill="black", colour="black", size=0, linetype="solid"), panel_grid_major=plotnine.element_line( size=0, linetype="solid", colour="black"), panel_grid_minor=plotnine.element_line( size=0, linetype="solid", colour="black"), strip_text=plotnine.element_text(size=text_size), ) + plotnine.facet_wrap("~cluster", ncol=n_columns) + plotnine.ggtitle("nUMI from each cell type") + plotnine.theme(figure_size=figure_size)) return ax
+ geom_errorbar(all_svcca, aes(x=lst_num_partitions, ymin='ymin', ymax='ymax'), color='darkgrey') \ + geom_line(threshold, aes(x=lst_num_partitions, y='score'), linetype='dashed', size=1, color="darkgrey", show_legend=False) \ + labs(x = "Number of Partitions", y = "Similarity score (SVCCA)", title = "Similarity across varying numbers of partitions") \ + theme( plot_background=element_rect(fill="white"), panel_background=element_rect(fill="white"), panel_grid_major_x=element_line(color="lightgrey"), panel_grid_major_y=element_line(color="lightgrey"), axis_line=element_line(color="grey"), legend_key=element_rect(fill='white', colour='white'), legend_title=element_text(family='sans-serif', size=15), legend_text=element_text(family='sans-serif', size=12), plot_title=element_text(family='sans-serif', size=15), axis_text=element_text(family='sans-serif', size=12), axis_title=element_text(family='sans-serif', size=15) ) \ + scale_color_manual(['#1976d2', '#b3e5fc']) \ print(panel_A) ggsave(plot=panel_A, filename=svcca_file, device="svg", dpi=300) ggsave(plot=panel_A, filename=svcca_png_file, device="svg", dpi=300)
def test_add_partial_complete(): theme1 = theme(axis_line_x=element_line()) theme2 = theme_gray() theme3 = theme1 + theme2 assert theme3 == theme2 def test_add_empty_theme_element(): # An empty theme element does not alter the theme theme1 = theme_gray() + theme(axis_line_x=element_line(color='red')) theme2 = theme1 + theme(axis_line_x=element_line()) assert theme1 == theme2 l1 = element_line(color='red', size=1, linewidth=1, linetype='solid') l2 = element_line(color='blue', size=2, linewidth=2) l3 = element_line(color='blue', size=2, linewidth=2, linetype='solid') blank = element_blank() def test_add_element_heirarchy(): # parent themeable modifies child themeable theme1 = theme_gray() + theme(axis_line_x=l1) # child theme2 = theme1 + theme(axis_line=l2) # parent theme3 = theme1 + theme(axis_line_x=l3) # child, for comparison assert theme2.themeables['axis_line_x'] == \ theme3.themeables['axis_line_x'] theme1 = theme_gray() + theme(axis_line_x=l1) # child theme2 = theme1 + theme(line=l2) # grand-parent
print(g_pca) ggsave(plot=g_pca, filename=pca_file, dpi=300) # In[16]: # Plot - black g_pca = ggplot(all_data_df, aes(x='PC1', y='PC2')) + geom_point(aes(color='No. of partitions'), alpha=0.1) + facet_wrap('~Comparison') + labs(x = "PC 1", y = "PC 2", title = "PCA of partition 1 vs multiple partitions") + theme( plot_background=element_rect(fill='black'), legend_title_align = "center", legend_background=element_rect(fill='black', colour='black'), legend_key=element_rect(fill='black', colour='black'), legend_title=element_text(colour="white"), legend_text=element_text(colour="white"), plot_title=element_text(weight='bold', colour="white"), panel_background=element_rect(fill="black"), axis_line=element_line(color="white"), axis_text=element_text(color="white"), panel_grid=element_line(colour="gray"), strip_text=element_text(colour="white"), strip_background=element_blank() ) \ + guides(colour=guide_legend(override_aes={'alpha': 1})) \ + scale_colour_manual(['#bdbdbd', '#b3e5fc']) print(g_pca) ggsave(plot=g_pca, filename=pca_blk_file, dpi=300) # ## Visualize multiple experiments in UMAP space # In[ ]: