def test_default_thetalocator(): # Ideally we would check AAAABBC, but the smallest axes currently puts a # single tick at 150° because MaxNLocator doesn't have a way to accept 15° # while rejecting 150°. fig, axs = plt.subplot_mosaic("AAAABB.", subplot_kw={"projection": "polar"}) for ax in axs.values(): ax.set_thetalim(0, np.pi) for ax in axs.values(): ticklocs = np.degrees(ax.xaxis.get_majorticklocs()).tolist() assert pytest.approx(90) in ticklocs assert pytest.approx(100) not in ticklocs
def plot_setup(pipeline): plt.style.use("default") defaults = { "layout": [ ["Data space", "Histogram model"], ["Losses", "Metrics"], ] } if pipeline.plot_kwargs is not None: for k in defaults: if k in pipeline.plot_kwargs: defaults[k] = pipeline.plot_kwargs[k] plt.rcParams.update({ "axes.labelsize": 13, "axes.linewidth": 1.2, "xtick.labelsize": 13, "ytick.labelsize": 13, "figure.figsize": [10.0, 10.0], "font.size": 13, "xtick.major.size": 3, "ytick.major.size": 3, "legend.fontsize": 11, "legend.fancybox": True, }) plt.rc("figure", dpi=150) fig, axs = plt.subplot_mosaic(defaults["layout"]) for label, ax in axs.items(): ax.set_title(label, fontstyle="italic") # axs["Example KDE"].set_title("Example KDE (nominal bkg)", fontstyle="italic") if "Histogram model" in axs: axins = axs["Histogram model"].inset_axes([0.33, 0.79, 0.3, 0.2]) axins.axis("off") axins_cpy = axins else: axins = axins_cpy = None ax_cpy = axs if pipeline.animate: camera = Camera(fig) else: camera = None plt.suptitle(pipeline.plot_title, fontsize="x-large") return dict(camera=camera, axs=axs, axins=axins, ax_cpy=ax_cpy, axins_cpy=axins_cpy, fig=fig)
def make_brain_figure(views, brain, cbar=None, vmin=None, vmax=None, cbar_label="", cbar_orient="vertical", hide_cbar=False): img_list = [] for k,v in views.items(): brain.show_view(**v) scr = brain.screenshot() img_list.append(scr) width = 3*scr.shape[0]/100 height = scr.shape[1]/100 cb_ratio = 6 pans = ["A", "B", "C"] if cbar: width += width * 1/cb_ratio mos_str = "" if cbar_orient == "vertical": for pan in pans: for x in range(cb_ratio): mos_str += pan mos_str += "D" elif cbar_orient == "horizontal": for x in range(cb_ratio): for pan in pans: mos_str += pan mos_str += "\n" mos_str += "D"*len(pans) fig, axes = plt.subplot_mosaic(mos_str, figsize=(width, height)) for img_mos, img in zip(pans, img_list): axes[img_mos].imshow(img) axes[img_mos].axis("off") if not hide_cbar: norm = Normalize(vmin, vmax) scalmap = cm.ScalarMappable(norm, cbar) plt.colorbar(scalmap, cax=axes["D"], orientation=cbar_orient) axes["D"].tick_params(labelsize=48) if cbar_orient == "horizontal": axes["D"].set_xlabel(cbar_label, fontsize=48) else: axes["D"].set_ylabel(cbar_label, fontsize=48) else: axes["D"].axis("off") else: fig, axes = plt.subplots(1, 3, figsize=(width, height)) for ax, img in zip(axes, img_list): ax.imshow(img) ax.axis("off") return fig
def test_shared_polar_keeps_ticklabels(): fig, axs = plt.subplots(2, 2, subplot_kw={"projection": "polar"}, sharex=True, sharey=True) fig.canvas.draw() assert axs[0, 1].xaxis.majorTicks[0].get_visible() assert axs[0, 1].yaxis.majorTicks[0].get_visible() fig, axs = plt.subplot_mosaic("ab\ncd", subplot_kw={"projection": "polar"}, sharex=True, sharey=True) fig.canvas.draw() assert axs["b"].xaxis.majorTicks[0].get_visible() assert axs["b"].yaxis.majorTicks[0].get_visible()
def radar_mosaic(radar_height=0.915, title_height=0.06, figheight=14): """ Create a Radar chart flanked by a title and endnote axes. Parameters ---------- radar_height: float, default 0.915 The height of the radar axes in fractions of the figure height (default 91.5%). title_height: float, default 0.06 The height of the title axes in fractions of the figure height (default 6%). figheight: float, default 14 The figure height in inches. Returns ------- fig : matplotlib.figure.Figure axs : dict[label, Axes] """ if title_height + radar_height > 1: error_msg = 'Reduce one of the radar_height or title_height so the total is ≤ 1.' raise ValueError(error_msg) endnote_height = 1 - title_height - radar_height figwidth = figheight * radar_height figure, axes = plt.subplot_mosaic( [['title'], ['radar'], ['endnote']], gridspec_kw={ 'height_ratios': [title_height, radar_height, endnote_height], # the grid takes up the whole of the figure 0-1 'bottom': 0, 'left': 0, 'top': 1, 'right': 1, 'hspace': 0 }, figsize=(figwidth, figheight)) axes['title'].axis('off') axes['endnote'].axis('off') return figure, axes
def subplot_mosaic(*args, **kwargs): """ Wrapper around matplotlib.pyplot.subplot_mosiac Automatically incorporates the PulseProgram projection in subplot keywords """ register_projection(PulseProgram) if "subplot_kw" in kwargs.keys(): if "projection" in kwargs["subplot_kw"]: warn( f"Projection will be set to 'PulseProgram' instead of {kwargs['subplot_kw']['projection']}" ) kwargs["subplot_kw"]["projection"] = "PulseProgram" else: kwargs["subplot_kw"] = {"projection": "PulseProgram"} fig, ax = plt.subplot_mosaic(*args, **kwargs) return fig, ax
# and formatters appropriate to the norm. These can be changed as for # other Axis objects. # # # Working with multiple Figures and Axes # ====================================== # # You can open multiple Figures with multiple calls to # ``fig = plt.figure()`` or ``fig2, ax = plt.subplots()``. By keeping the # object references you can add Artists to either Figure. # # Multiple Axes can be added a number of ways, but the most basic is # ``plt.subplots()`` as used above. One can achieve more complex layouts, # with Axes objects spanning columns or rows, using `~.pyplot.subplot_mosaic`. fig, axd = plt.subplot_mosaic([['upleft', 'right'], ['lowleft', 'right']], layout='constrained') axd['upleft'].set_title('upleft') axd['lowleft'].set_title('lowleft') axd['right'].set_title('right') ############################################################################### # Matplotlib has quite sophisticated tools for arranging Axes: See # :doc:`/tutorials/intermediate/arranging_axes` and # :doc:`/tutorials/provisional/mosaic`. # # # More reading # ============ # # For more plot types see :doc:`Plot types </plot_types/index>` and the # :doc:`API reference </api/index>`, in particular the
def make_plot(config, params, isr_tables, cost_tables, filename=None): # expand some parameters n_freq = params["n_freq"] n_chan = params["n_chan"] pca = params["pca"] # construct the mosaic n_algos = len(include_algos) assert 2 * n_algos + 2 <= len(ascii_letters) mosaic_array = [[ascii_letters[0] * n_algos], [ascii_letters[1] * n_algos]] for b in range(2): for i in range(1, n_algos + 1): mosaic_array[b].append(ascii_letters[2 * i + b]) mosaic = "\n".join(["".join(a) for a in mosaic_array]) fig, axes = plt.subplot_mosaic(mosaic) map_up = [mosaic_array[0][0][0]] + mosaic_array[0][1:] map_do = [mosaic_array[1][0][0]] + mosaic_array[1][1:] n_bins = 30 y_lim_isr = [0, 1] y_lim_cost = [0, 1] x_lim_hist_isr = [0, 1.0] x_lim_hist_cost = [0, 1.0] for i, (algo, table) in enumerate(isr_tables.items()): n_iter = config["algos"][algo]["kwargs"]["n_iter"] algo_name = config["algos"][algo]["algo"] if bss.is_dual_update[algo_name]: callback_checkpoints = np.arange(0, n_iter + 1, 2) else: callback_checkpoints = np.arange(0, n_iter + 1) if not algo.startswith("fullhead"): # isr y_lim_isr = [ min(y_lim_isr[0], table.min()), max(y_lim_isr[1], table.max()), ] # cost y_lim_cost = [ min(y_lim_cost[0], cost_tables[algo].min()), max(y_lim_cost[1], np.percentile(cost_tables[algo], 0.9)), ] I_s = table[:, -1] < fail_thresh # separation is sucessful I_f = table[:, -1] >= fail_thresh # separation fails # ISR convergence p = axes[map_up[0]].semilogx( np.array(callback_checkpoints) + 1, np.mean(table[I_s, :], axis=0), label=algo, ) c = p[0].get_color() axes[map_up[0]].plot( np.array(callback_checkpoints) + 1, np.mean(table[I_f, :], axis=0), label=algo, alpha=0.6, c=c, ) # Cost axes[map_do[0]].semilogx( np.array(callback_checkpoints) + 1, np.mean(cost_tables[algo], axis=0), label=algo, ) # Histograms axes[map_up[i + 1]].hist(table[:, -1], bins=n_bins, orientation="horizontal", density=True) axes[map_do[i + 1]].hist( cost_tables[algo][:, -1], bins=n_bins, orientation="horizontal", density=True, ) axes[map_up[i + 1]].set_title(title_dict[algo]) axes[map_up[i + 1]].set_xlabel("") for i in range(len(isr_tables) + 1): axes[map_up[i]].set_ylim(y_lim_isr) axes[map_do[i]].set_ylim(y_lim_cost) if i > 0: axes[map_up[i]].set_yticks([]) axes[map_do[i]].set_yticks([]) """ axes[map_up[i]].set_xlim(x_lim_hist_isr) axes[map_do[i]].set_xlim(x_lim_hist_cost) """ axes[map_up[0]].legend() axes[map_do[0]].legend() axes[map_do[0]].set_xlabel("Iteration") axes[map_up[0]].set_ylabel("ISR [dB]") axes[map_do[0]].set_ylabel("Cost") return fig, axes
def main(): # Validate cli args = cli() valid_args = validate_args(args) if not valid_args: return False # Set figure theme sns.set_theme(style='white') # setup sub plot using mosaic layout gs_kw = dict(width_ratios=[1, 1, 0.5], height_ratios=[1, 1]) f, ax = plt.subplot_mosaic([['p1', 'p2', '.'], ['p3', 'p4', '.'], ], gridspec_kw=gs_kw, figsize=(7.5, 5), constrained_layout=True) input_dir = pathlib.Path(args.input_dir) # common palette colours = sns.color_palette("viridis", len(SMALL_POP_SIZES+LARGE_POP_SIZES)) custom_palette = {v: colours[i] for i, v in enumerate(SMALL_POP_SIZES+LARGE_POP_SIZES)} # SMALL_POP_BF_CSV_FILENAME # Load per simulation step data into data frame (strip any white space) df = pd.read_csv(input_dir/SMALL_POP_BF_CSV_FILENAME, sep=',', quotechar='"') df.columns = df.columns.str.strip() # select subset of the pop sizes for plotting df = df[df['pop_size'].isin(SMALL_POP_SIZES)] # calculate baseline and the speedup df_baseline = df.query('ensemble_size == 1').groupby('pop_size', as_index=False).mean()[['pop_size', 's_sim_mean']] df = df.merge(df_baseline, left_on='pop_size', right_on='pop_size', suffixes=('', '_baseline')) df["speedup"] = df['s_sim_mean_baseline'] / df['s_sim_mean'] # Plot popsize brute force plt_df_bf = sns.lineplot(x='ensemble_size', y='speedup', hue='pop_size', style='pop_size', data=df, palette=custom_palette, ax=ax['p1'], ci="sd") plt_df_bf.set(xlabel='', ylabel='Speedup') # set tick formatting, title and hide legend ax['p1'].yaxis.set_major_formatter(FormatStrFormatter('%0.1f')) ax['p1'].set_title(label='A', loc='left', fontweight="bold") ax['p1'].legend().set_visible(False) # SMALL_POP_SPATIAL_CSV_FILENAME # Load per simulation step data into data frame (strip any white space) df = pd.read_csv(input_dir/SMALL_POP_SPATIAL_CSV_FILENAME, sep=',', quotechar='"') df.columns = df.columns.str.strip() # select subset of the pop sizes for plotting df = df[df['pop_size'].isin(SMALL_POP_SIZES)] # calculate baseline and the speedup df_baseline = df.query('ensemble_size == 1').groupby('pop_size', as_index=False).mean()[['pop_size', 's_sim_mean']] df = df.merge(df_baseline, left_on='pop_size', right_on='pop_size', suffixes=('', '_baseline')) df["speedup"] = df['s_sim_mean_baseline'] / df['s_sim_mean'] # Plot popsize brute force plt_df_bf = sns.lineplot(x='ensemble_size', y='speedup', hue='pop_size', style='pop_size', data=df, palette=custom_palette, ax=ax['p2'], ci="sd") plt_df_bf.set(xlabel='', ylabel='') # set tick formatting, title and hide legend ax['p2'].yaxis.set_major_formatter(FormatStrFormatter('%0.1f')) ax['p2'].set_title(label='B', loc='left', fontweight="bold") ax['p2'].legend().set_visible(False) # LARGE_POP_BF_CSV_FILENAME # Load per simulation step data into data frame (strip any white space) df = pd.read_csv(input_dir/LARGE_POP_BF_CSV_FILENAME, sep=',', quotechar='"') df.columns = df.columns.str.strip() # select subset of the pop sizes for plotting df = df[df['pop_size'].isin(LARGE_POP_SIZES)] # calculate baseline and the speedup df_baseline = df.query('ensemble_size == 1').groupby('pop_size', as_index=False).mean()[['pop_size', 's_sim_mean']] df = df.merge(df_baseline, left_on='pop_size', right_on='pop_size', suffixes=('', '_baseline')) df["speedup"] = df['s_sim_mean_baseline'] / df['s_sim_mean'] # Plot popsize brute force plt_df_bf = sns.lineplot(x='ensemble_size', y='speedup', hue='pop_size', style='pop_size', data=df, palette=custom_palette, ax=ax['p3'], ci="sd") plt_df_bf.set(xlabel='E', ylabel='Speedup') # set tick formatting, title and hide legend ax['p3'].yaxis.set_major_formatter(FormatStrFormatter('%0.1f')) ax['p3'].set_title(label='C', loc='left', fontweight="bold") ax['p3'].legend().set_visible(False) # LARGE_POP_SPATIAL_CSV_FILENAME # Load per simulation step data into data frame (strip any white space) df = pd.read_csv(input_dir/LARGE_POP_SPATIAL_CSV_FILENAME, sep=',', quotechar='"') df.columns = df.columns.str.strip() # select subset of the pop sizes for plotting df = df[df['pop_size'].isin(LARGE_POP_SIZES)] # calculate baseline and the speedup df_baseline = df.query('ensemble_size == 1').groupby('pop_size', as_index=False).mean()[['pop_size', 's_sim_mean']] df = df.merge(df_baseline, left_on='pop_size', right_on='pop_size', suffixes=('', '_baseline')) df["speedup"] = df['s_sim_mean_baseline'] / df['s_sim_mean'] # Plot popsize brute force plt_df_bf = sns.lineplot(x='ensemble_size', y='speedup', hue='pop_size', style='pop_size', data=df, palette=custom_palette, ax=ax['p4'], ci="sd") plt_df_bf.set(xlabel='E', ylabel='') # set tick formatting, title and hide legend ax['p4'].yaxis.set_major_formatter(FormatStrFormatter('%0.1f')) ax['p4'].set_title(label='D', loc='left', fontweight="bold") ax['p4'].legend().set_visible(False) # Figure Legend from unique lines in pallet lines_labels = [ax.get_legend_handles_labels() for ax in f.axes] lines, labels = [sum(lol, []) for lol in zip(*lines_labels)] unique = {k:v for k, v in zip(labels, lines)} f.legend(unique.values(), unique.keys(), loc='upper right', title='N') # Save to image #f.tight_layout() output_dir = pathlib.Path(args.output_dir) f.savefig(output_dir/"paper_figure.png", dpi=args.dpi) f.savefig(output_dir/"paper_figure.pdf", format='pdf', dpi=args.dpi)
a[2,1].set(title='Soil pH',ylim=(maxdepth,0),xlabel='Soil pH',ylabel='Soil depth (m)') for num in range(len(snapshots)): for ax in a[:,0]: ax.axvline(ax.xaxis.convert_units(t[snapshots[num]].item()),ls=snapshot_styles[num],c='gray',lw=2.0) a[0,1].plot(Fe2.isel(time=snapshots[num]),z,ls=snapshot_styles[num],c='gray') a[1,1].plot(FeOxide.isel(time=snapshots[num]),z,ls=snapshot_styles[num],c='gray') a[2,1].plot(pH.isel(time=snapshots[num]),z,ls=snapshot_styles[num],c='gray') if 'SIC_vr' in data: calcite=data['SIC_vr'].T.squeeze()[:10,:] # f,a=plt.subplots(num='Calcite',clear=True,nrows=1,ncols=2,gridspec_kw={'width_ratios':[1,0.5]},figsize=(6,3)) f,a=plt.subplot_mosaic( ''' AB C. ''', gridspec_kw={'width_ratios':[1,0.5],'height_ratios':[1,0.5]},num='Soil inorganic C',clear=True, ) (calcite).plot(ax=a['A'],cbar_kwargs={'label':'Soil inorganic C concentration (mol C/m$^3$)'}) a['B'].plot((calcite).mean(dim='time'),z) a['A'].set(title='Soil inorganic C concentration',ylim=(maxdepth,0),xlabel='Time (year)',ylabel='Soil depth (m)') a['B'].set(title='Soil inorganic C concentration',ylim=(maxdepth,0),xlabel='Soil inorganic C (mol C/m$^3$)',ylabel='Soil depth (m)') (calcite*dz[:,None]).sum(dim='levdcmp').plot(ax=a['C']) a['C'].set(title='Column total soil inorganic C',xlabel='Time (year)',ylabel='Total soil inorganic C (g C/m$^2$)',xlim=a['A'].get_xlim()) f,a=plt.subplots(num='Carbon time series',clear=True,nrows=2) data['TOTSOMC'].plot(ax=a[0],label='Total SOM C') data['TOTLITC'].plot(ax=a[0],label='Total litter C') data['TOTVEGC'].plot(ax=a[0],label='Total vegetation C') a[0].set(title='C pools',xlabel='Time (year)',ylabel='C stock (g C m$^{-2}$')
# # this is bottom right # xy=(1, 0), # this is the top left xy=(0, 1), xycoords="axes fraction", # units are absolute offset in points from xy xytext=(-5, 5), textcoords=("offset points"), # set the text alignment ha="right", va="bottom", fontweight="bold", fontsize="larger", ) # %% fig, ax_dict = plt.subplot_mosaic([["raw", "omega"], ["raw", "zeta"]], constrained_layout=True) indx = [0, 10, 24] plot_several(ax_dict["raw"], d[indx], [fits[i] for i in indx]) plot_zeta(ax_dict["zeta"], fits_df) plot_omega(ax_dict["omega"], fits_df) fig.align_ylabels(list(ax_dict.values())) for k, v in {"raw": "a", "omega": "b", "zeta": "c"}.items(): subplot_label(ax_dict[k], f"({v})") # %% out = Path("../../slides/figs") / Path(__file__).with_suffix(".pdf").name fig.savefig(out)
lowest_interesting_E = -1.1 highest_interesting_E = -0.5 lowest_interesting_T = 0.008 exact = np.load(os.path.join('.', 'thesis-data-new', system.name() + '.npz')) correct_S = exact['correct_S'] E = exact['E'] dE = E[1] - E[0] paths = glob.glob(os.path.join('thesis-data-new', '*.npz')) subplot_fig, axs = plt.subplot_mosaic( [['(a)', '(b)'], ['(c)', '(d)']], tight_layout=True, figsize=(13, 9), ) plt.figure('latest-entropy') plt.plot(E, correct_S, ':', label='exact', linewidth=2) axs['(c)'].plot(E, correct_S, ':', label='exact', linewidth=2) fig, ax = plt.subplots(figsize=[5, 4], num='latest-heat-capacity') axins = ax.inset_axes( 0.5 * np.array([1, 1, 0.47 / 0.5, 0.47 / 0.5])) #[0.005, 0.012, 25, 140]) axins_subplot = axs['(d)'].inset_axes(0.5 * np.array([1, 1, 0.47 / 0.5, 0.47 / 0.5])) heat_capacity.plot_from_data(exact['T'], exact['correct_C'],
txt_w, txt_h = 0, 0.85 mos_str = """ AAAAV BBBBW CCCCX DDDDY EEEEZ """ mos_str = """ A B C D E """ fig, axes = plt.subplot_mosaic(mos_str, figsize=(21.6, 21.6)) img_a = np.load("../images/theta0_task.npy") img_b = np.load("../images/params_bar_theta_0.npy") img = np.concatenate((img_a, img_b[..., :3]), axis=1) axes["A"].imshow(img) axes["A"].text(txt_w, txt_h, "A| Theta general task", transform=axes["A"].transAxes, fontsize=fs) img_a = np.load("../images/alpha0_task.npy") img_b = np.load("../images/params_bar_alpha_0.npy") img = np.concatenate((img_a, img_b[..., :3]), axis=1) axes["B"].imshow(img)
# =============== # # The location of the legend can be specified by the keyword argument # *loc*. Please see the documentation at :func:`legend` for more details. # # The ``bbox_to_anchor`` keyword gives a great degree of control for manual # legend placement. For example, if you want your axes legend located at the # figure's top right-hand corner instead of the axes' corner, simply specify # the corner's location and the coordinate system of that location:: # # ax.legend(bbox_to_anchor=(1, 1), # bbox_transform=fig.transFigure) # # More examples of custom legend placement: fig, ax_dict = plt.subplot_mosaic([['top', 'top'], ['bottom', 'BLANK']], empty_sentinel="BLANK") ax_dict['top'].plot([1, 2, 3], label="test1") ax_dict['top'].plot([3, 2, 1], label="test2") # Place a legend above this subplot, expanding itself to # fully use the given bounding box. ax_dict['top'].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left', ncol=2, mode="expand", borderaxespad=0.) ax_dict['bottom'].plot([1, 2, 3], label="test1") ax_dict['bottom'].plot([3, 2, 1], label="test2") # Place a legend to the right of this smaller subplot. ax_dict['bottom'].legend(bbox_to_anchor=(1.05, 1), loc='upper left',
def test_fail_list_of_str(self): with pytest.raises(ValueError, match='must be 2D'): plt.subplot_mosaic(['foo', 'bar']) with pytest.raises(ValueError, match='must be 2D'): plt.subplot_mosaic(['foo'])
return line / line[0] * ttDofs[0] def to_float(_int): try: return np.float_(_int) except OverflowError: return np.nan print("\nTime points:", np.linspace(0, 1, NUM_STEPS)) mosaic = """ AABB """ fig, ax = plt.subplot_mosaic(mosaic) ylim = (1e-12, 1e4) print("\nUnsorted") print("========") allRanks, allDegrees = load_parameters("unsorted_parameters.json") allNumAssets = np.array([2, 3, 5, 10, 20, 30, 50, 100, 200, 500, 750, 1000], dtype=object) ttDofs = [] sparseDofs = [] fullDofs = [] for numAssets in allNumAssets: tt, sparse, full = dofs(numAssets) ttDofs.append(tt) sparseDofs.append(sparse) fullDofs.append(full)
############################################################################### # It is also possible to show images of pictures. # A sample image with cbook.get_sample_data('grace_hopper.jpg') as image_file: image = plt.imread(image_file) # And another image, using 256x256 16-bit integers. w, h = 256, 256 with cbook.get_sample_data('s1045.ima.gz') as datafile: s = datafile.read() A = np.frombuffer(s, np.uint16).astype(float).reshape((w, h)) extent = (0, 25, 0, 25) fig, ax = plt.subplot_mosaic([['hopper', 'mri']], figsize=(7, 3.5)) ax['hopper'].imshow(image) ax['hopper'].axis('off') # clear x-axis and y-axis im = ax['mri'].imshow(A, cmap=plt.cm.hot, origin='upper', extent=extent) markers = [(15.9, 14.5), (16.8, 15)] x, y = zip(*markers) ax['mri'].plot(x, y, 'o') ax['mri'].set_title('MRI') plt.show() ###############################################################################
================== Labelling subplots is relatively straightforward, and varies, so Matplotlib does not have a general method for doing this. Simplest is putting the label inside the axes. Note, here we use `.pyplot.subplot_mosaic`, and use the subplot labels as keys for the subplots, which is a nice convenience. However, the same method works with `.pyplot.subplots` or keys that are different than what you want to label the subplot with. """ import matplotlib.pyplot as plt import matplotlib.transforms as mtransforms fig, axs = plt.subplot_mosaic([['a)', 'c)'], ['b)', 'c)'], ['d)', 'd)']], constrained_layout=True) for label, ax in axs.items(): # label physical distance in and down: trans = mtransforms.ScaledTranslation(10 / 72, -5 / 72, fig.dpi_scale_trans) ax.text(0.0, 1.0, label, transform=ax.transAxes + trans, fontsize='medium', verticalalignment='top', fontfamily='serif', bbox=dict(facecolor='0.7', edgecolor='none', pad=3.0)) plt.show()
plot_cmap=False, basecolors=list(publication_colors.values()), close_plt=False, figsize=(20, 15), file="Figures/PublicationPlots/Figure1_MapClusters") PlotClusterGroups(k=9, title="", figsize=(20, 15), basecolors=list(publication_colors.values()), file="Figures/PublicationPlots/Figure1_MapClusters_wCmap") # %% ############# FIG 3 - FOOD PRODUCTION AND CULTIVATION COSTS ############## fig, axd = plt.subplot_mosaic( [["upper left", "right"], ["lower left", "right"]], figsize=(25, 16), gridspec_kw={"width_ratios": [1.3, 1]}) fig.subplots_adjust(hspace=0.3) ## PANEL A, B - FOOD PRODUCTION DISTRIBUTION # Stationary scenario (fixed population, fixed yield distributions) # Food production distribution (over all years, which is ok as all years behave # the same as we use the stationary scenario) for changing probability for food # security # Each cluster as separate plot (one good and one bad will be used in main text) p = "fixed" y = "fixed" for (cl, panel) in [(4, "(b)"), (5, "(a)")]:
"labels": reg_arranged }, { "col_key": { "lh": (.5, .5, .5, 0.35), "rh": (.5, .5, .5, 0.5) }, "labels": hemi_arranged }] # estimated parameters mos_str = """ AAAABBBBCCCCX DDDDEEEEFFFFY """ ax_names = ["A", "B", "C", "D", "E", "F"] fx_fig, fx_axes = plt.subplot_mosaic(mos_str, figsize=(76.8, 38.4)) # get universal vmin, vmax all_vals = np.concatenate(list(cnx_params.values())) vmin, vmax = np.min(all_vals), np.max(all_vals) conds = [ "Resting state", "Audio task", "Visual task", "Visual w/distraction", "Counting backwards", "General task" ] stat_conds += ["task"] for ax_n, cond, stat_cond in zip(ax_names, conds, stat_conds): img = annotated_matrix(cnx_params[stat_cond], label_names, annot_labels, annot_vert_pos="left", annot_hor_pos="bottom", overlay=True,
transform=ax.transAxes, ha="center", va="center", fontsize=fontsize, color="darkgrey") ############################################################################## # The same effect can be achieved with `~.pyplot.subplot_mosaic`, # but the return type is a dictionary instead of an array, where the user # can give the keys useful meanings. Here we provide two lists, each list # representing a row, and each element in the list a key representing the # column. fig, axd = plt.subplot_mosaic( [['upper left', 'upper right'], ['lower left', 'lower right']], figsize=(5.5, 3.5), constrained_layout=True) for k in axd: annotate_axes(axd[k], f'axd["{k}"]', fontsize=14) fig.suptitle('plt.subplot_mosaic()') ############################################################################ # Axes spanning rows or columns in a grid # --------------------------------------- # # Sometimes we want Axes to span rows or columns of the grid. # There are actually multiple ways to accomplish this, but the most # convenient is probably to use `~.pyplot.subplot_mosaic` by repeating one # of the keys: fig, axd = plt.subplot_mosaic(
for dname in data: db2 = pd.read_csv(dname + '/database_entries_processed.csv') x = db2["X [mm]"].to_numpy(copy=True) y = db2["Y [mm]"].to_numpy(copy=True) qual = db2["GPS quality"].to_numpy(copy=True) fnames = db2["Filename"] dirname = dname + "/frames_deg_{}".format(degree) os.makedirs(dirname, exist_ok=True) xa = db2["fitted x deg {}".format(degree)].to_numpy(copy=True) ya = db2["fitted y deg {}".format(degree)].to_numpy(copy=True) gps_h = db2["gps_h deg {}".format(degree)].to_numpy(copy=True) ch = db2["corrected IMU heading [degrees]"].to_numpy(copy=True) gps_h_a = deg_to_rad(gps_h) ch_a = deg_to_rad(ch) fig, ax = plt.subplot_mosaic([["overview", "detail"], ["view", "view"]]) ax["overview"].plot(xa, ya, lw=0.2) ax["detail"].plot(xa, ya, lw=0.2) ax["detail"].scatter(xa, ya, s=0.1) ax["detail"].scatter(x, y, s=0.1) ax["detail"].quiver(x, y, 1000 * np.cos(gps_h_a), 1000 * np.sin(gps_h_a), units='dots', angles='xy', scale_units='xy', scale=25, color='r') ax["detail"].quiver(x, y,
plt.close() for diff in [True, False]: for j, field in enumerate(fields): print(field) for season in seasons: print(' ' + season) fig2, axd = plt.subplot_mosaic( [['.', 'Chukchi_Sea_NSIDC', 'Bering_Sea', '.'], [ 'Beaufort_Sea_NSIDC', 'region', 'region', 'East_Siberian_Sea_NSIDC' ], [ 'Canadian_Archipelago_NSIDC', 'region', 'region', 'Laptev_Sea_NSIDC' ], ['Hudson_Bay_NSIDC', 'region', 'region', 'Kara_Sea'], ['Baffin_Bay_NSIDC', 'region', 'region', 'Barents_Sea'], ['.', 'Greenland_Sea', 'Central_Arctic_NSIDC', '.']], figsize=(12, 9)) xx = axd['region'].get_subplotspec() axd['region'].remove() axd['region'] = fig2.add_subplot( xx, projection=ccrs.NorthPolarStereo()) plot_regions(axd['region']) for i, region in enumerate(regions): print(' ' + region)
background = (1, 1, 1) fontsize = 150 img_rat = 8 pans = ["A", "B", "C", "D"] pads = ["Z", "Y", "X", "W"] descs = ["General", "Auditory", "Visual", "Aud. distraction"] mos_str = "" pad = True for pan, pad in zip(pans, pads): for idx in range(img_rat): mos_str += pan + "\n" if pad: mos_str += pad + "\n" mos_str += "E" fig, axes = plt.subplot_mosaic(mos_str, figsize=(64.80, 90.00)) for desc, pan in zip(descs, pans): axes[pan].set_title("{} task".format(desc), fontsize=fontsize) axes[pan].axis("off") for pad in pads: axes[pad].axis("off") params = aic_comps["sig_params"].copy() simp_params = np.expand_dims(aic_comps["simp_params"].copy()[:, 1], 1) params = np.concatenate((params, simp_params), axis=1) params_n = param_norm(params) vmin = -abs(params).max() vmax = abs(params).max() param_n = params_n[:, -1] rgba = params_to_rgba(param_n)
# for plotting. Again the method takes a waiting time to select the spectrum for # extraction. Additionally, it takes parameters to shift the position of the # diagonal used for extraction. If not given, it goes through the position of # the minimum. diag_result = ds.diag_and_antidiag(0.2) fig, ax = plt.subplots() ax.plot(ds.probe_wn, diag_result.diag) ax.plot(ds.probe_wn, diag_result.antidiag) plot_helpers.lbl_spec(ax) # %% # The additional attributes of the result-object can be used to draw lines in the spectrum. fig, ax = plt.subplot_mosaic('AABB', figsize=(5, 2), constrained_layout=True) pm = ax['A'].pcolormesh(ds.probe_wn, ds.pump_wn, ds.spec2d[ds.t_idx(1), :, :].T, shading='auto', cmap='seismic') ax['A'].plot(ds.probe_wn, diag_result.diag_coords, lw=1, c="y", ls='--') ax['A'].plot(ds.probe_wn, diag_result.antidiag_coords, lw=1, c="c", ls='--') ax['A'].set(ylim=(ds.pump_wn.min(), ds.pump_wn.max()), ylabel=plot_helpers.freq_label) ax['A'].set_xlabel(plot_helpers.freq_label) fig.colorbar(pm, ax=ax['A'], shrink=0.69, pad=0) ax['B'].plot(ds.probe_wn, diag_result.diag, c='y') ax['B'].plot(ds.probe_wn, diag_result.antidiag, c='c')
pans = ["A", "B", "C", "D", "E"] pads = ["Z", "Y", "X", "W", "V"] descs = [ "General task", "Auditory task", "Visual task", "Aud. distraction task", "Rainbow" ] conds = ["simple_task", "audio", "visual", "visselten", "rainbow"] mos_str = "" pad = True for pan, pad in zip(pans, pads): for idx in range(img_rat): mos_str += pan + "\n" if pad: mos_str += pad + "\n" fig, axes = plt.subplot_mosaic(mos_str, figsize=(64.8, 108)) for desc, pan in zip(descs, pans): axes[pan].set_title("{}".format(desc), fontsize=fontsize) axes[pan].axis("off") for pad in pads: axes[pad].axis("off") legend_props = [["Audio", "r"], ["Visual", "g"], ["Aud. Distr.", "b"]] for pan, desc, cond in zip(pans, descs, conds): if cond == "rainbow": img = make_brain_image(views, params_brains[cond], text=pan, text_loc="lup", text_pan=0, legend=legend_props,
""" Example of using Matplotlib subplot_mosaic() to create a grid of plots. """ import matplotlib.pyplot as plt _, ax = plt.subplot_mosaic([['one', 'two'], ['three', 'three']]) ax['one'].plot([3, 5, 6, 2, 8], '-o', color='red') ax['two'].plot([7, 8, 4, 9], color='blue') ax['three'].plot([1, 3, 4, 2, 3, 4], color='black') plt.show()
def main(): # Validate cli args = cli() valid_args = validate_args(args) if not valid_args: return False # Set figure theme sns.set_theme(style='white') # setup sub plot using mosaic layout gs_kw = dict(width_ratios=[1, 1, 0.5], height_ratios=[1, 1, 1, 1]) f, ax = plt.subplot_mosaic([ ['p1', 'p2', '.'], ['p3', 'p4', '.'], ['p5', 'p6', '.'], ['p7', 'p8', '.'], ], gridspec_kw=gs_kw, figsize=(7.5, 10), constrained_layout=True) input_dir = pathlib.Path(args.input_dir) # common palette colours = sns.color_palette("viridis", len(SMALL_POP_SIZES + LARGE_POP_SIZES)) custom_palette = { v: colours[i] for i, v in enumerate(SMALL_POP_SIZES + LARGE_POP_SIZES) } # SMALL_POP_BF_CSV_FILENAME # Load per simulation step data into data frame (strip any white space) df = pd.read_csv(input_dir / SMALL_POP_BF_CSV_FILENAME, sep=',', quotechar='"') df.columns = df.columns.str.strip() # Calculate speedup df_serial = df[(df.is_concurrent == 0)] df = df[(df.is_concurrent == 1)] df.reset_index(drop=True, inplace=True) df['speedup'] = df_serial['s_step_mean'] / df['s_step_mean'] # select subset of the pop sizes for plotting df = df[df['pop_size'].isin(SMALL_POP_SIZES)] # Plot speedup plot = sns.lineplot(x='num_species', y='speedup', hue='pop_size', style='pop_size', data=df, palette=custom_palette, ax=ax['p1'], ci="sd") plot.set(xlabel='', ylabel='Speedup') # set tick formatting, title and hide legend ax['p1'].yaxis.set_major_formatter(FormatStrFormatter('%0.1f')) ax['p1'].set_title(label='A', loc='left', fontweight="bold") ax['p1'].legend().set_visible(False) # Plot time plot = sns.lineplot(x='num_species', y='s_step_mean', hue='pop_size', style='pop_size', data=df, palette=custom_palette, ax=ax['p3'], ci="sd") plot.set(xlabel='', ylabel='Step time (s)') # set tick formatting, title and hide legend ax['p3'].set_title(label='C', loc='left', fontweight="bold") ax['p3'].legend().set_visible(False) # SMALL_POP_SPATIAL_CSV_FILENAME # Load per simulation step data into data frame (strip any white space) df = pd.read_csv(input_dir / SMALL_POP_SPATIAL_CSV_FILENAME, sep=',', quotechar='"') df.columns = df.columns.str.strip() # Calculate speedup df_serial = df[(df.is_concurrent == 0)] df = df[(df.is_concurrent == 1)] df.reset_index(drop=True, inplace=True) df['speedup'] = df_serial['s_step_mean'] / df['s_step_mean'] # select subset of the pop sizes for plotting df = df[df['pop_size'].isin(SMALL_POP_SIZES)] # Plot plt_df_bf = sns.lineplot(x='num_species', y='speedup', hue='pop_size', style='pop_size', data=df, palette=custom_palette, ax=ax['p2'], ci="sd") plt_df_bf.set(xlabel='', ylabel='') # set tick formatting, title and hide legend ax['p2'].yaxis.set_major_formatter(FormatStrFormatter('%0.1f')) ax['p2'].set_title(label='B', loc='left', fontweight="bold") ax['p2'].legend().set_visible(False) # Plot time plot = sns.lineplot(x='num_species', y='s_step_mean', hue='pop_size', style='pop_size', data=df, palette=custom_palette, ax=ax['p4'], ci="sd") plot.set(xlabel='', ylabel='') # set tick formatting, title and hide legend ax['p4'].set_title(label='D', loc='left', fontweight="bold") ax['p4'].legend().set_visible(False) # LARGE_POP_BF_CSV_FILENAME # Load per simulation step data into data frame (strip any white space) df = pd.read_csv(input_dir / LARGE_POP_BF_CSV_FILENAME, sep=',', quotechar='"') df.columns = df.columns.str.strip() # Calculate speedup df_serial = df[(df.is_concurrent == 0)] df = df[(df.is_concurrent == 1)] df.reset_index(drop=True, inplace=True) df['speedup'] = df_serial['s_step_mean'] / df['s_step_mean'] # select subset of the pop sizes for plotting df = df[df['pop_size'].isin(LARGE_POP_SIZES)] # Plot speedup plot = sns.lineplot(x='num_species', y='speedup', hue='pop_size', style='pop_size', data=df, palette=custom_palette, ax=ax['p5'], ci="sd") plot.set(xlabel='', ylabel='Speedup') # set tick formatting, title and hide legend ax['p5'].yaxis.set_major_formatter(FormatStrFormatter('%0.1f')) ax['p5'].set_title(label='E', loc='left', fontweight="bold") ax['p5'].legend().set_visible(False) # Plot time plot = sns.lineplot(x='num_species', y='s_step_mean', hue='pop_size', style='pop_size', data=df, palette=custom_palette, ax=ax['p7'], ci="sd") plot.set(xlabel='Species', ylabel='Step time (s)') # set tick formatting, title and hide legend ax['p7'].set_title(label='G', loc='left', fontweight="bold") ax['p7'].legend().set_visible(False) # LARGE_POP_SPATIAL_CSV_FILENAME # Load per simulation step data into data frame (strip any white space) df = pd.read_csv(input_dir / LARGE_POP_SPATIAL_CSV_FILENAME, sep=',', quotechar='"') df.columns = df.columns.str.strip() # Calculate speedup df_serial = df[(df.is_concurrent == 0)] df = df[(df.is_concurrent == 1)] df.reset_index(drop=True, inplace=True) df['speedup'] = df_serial['s_step_mean'] / df['s_step_mean'] # select subset of the pop sizes for plotting df = df[df['pop_size'].isin(LARGE_POP_SIZES)] # Plot speedup plot = sns.lineplot(x='num_species', y='speedup', hue='pop_size', style='pop_size', data=df, palette=custom_palette, ax=ax['p6'], ci="sd") plot.set(xlabel='', ylabel='') # set tick formatting, title and hide legend ax['p6'].yaxis.set_major_formatter(FormatStrFormatter('%0.1f')) ax['p6'].set_title(label='F', loc='left', fontweight="bold") ax['p6'].legend().set_visible(False) # Plot time plot = sns.lineplot(x='num_species', y='s_step_mean', hue='pop_size', style='pop_size', data=df, palette=custom_palette, ax=ax['p8'], ci="sd") plot.set(xlabel='Species', ylabel='') # set tick formatting, title and hide legend ax['p8'].set_title(label='H', loc='left', fontweight="bold") ax['p8'].legend().set_visible(False) # Figure Legend from unique lines in pallet lines_labels = [ax.get_legend_handles_labels() for ax in f.axes] lines, labels = [sum(lol, []) for lol in zip(*lines_labels)] unique = {k: v for k, v in zip(labels, lines)} f.legend(unique.values(), unique.keys(), loc='upper right', title='N') # Save to image and pdf (vector) output_dir = pathlib.Path(args.output_dir) f.savefig(output_dir / "paper_figure.png", dpi=args.dpi) f.savefig(output_dir / "paper_figure.pdf", format='pdf', dpi=args.dpi)
def main(): # Validate cli args = cli() valid_args = validate_args(args) if not valid_args: return False # Set figure theme sns.set_theme(style='white') # setup sub plot using mosaic layout gs_kw = dict(width_ratios=[1, 1], height_ratios=[1, 1, 1]) f, ax = plt.subplot_mosaic([ ['p1', 'p2'], ['p3', 'p4'], ['p5', '.'], ], gridspec_kw=gs_kw, figsize=(7.5, 7.5), constrained_layout=True) input_dir = pathlib.Path(args.input_dir) # common palette custom_palette = { "circles_bruteforce": "g", "circles_bruteforce_rtc": "r", "circles_spatial3D": "b", "circles_spatial3D_rtc": "k" } # Load per simulation step data into data frame (strip any white space) pop_df = pd.read_csv(input_dir / VARIABLE_POP_CSV_FILENAME, sep=',', quotechar='"') pop_df.columns = pop_df.columns.str.strip() # Plot popsize brute force scale_df_bf = pop_df.query( "model == 'circles_bruteforce_rtc' or model == 'circles_bruteforce'") plt_df_bf = sns.lineplot(x='agent_count', y='s_step_mean', hue='model', style='model', data=scale_df_bf, ax=ax['p1'], palette=custom_palette, ci="sd") # plt_df_bf.ticklabel_format(style='plain', axis='x') # no scientific notation plt_df_bf.set(xlabel='N', ylabel='Step time (s)') ax['p1'].set_title(label='A', loc='left', fontweight="bold") ax['p1'].legend().set_visible(False) # Plot spatial scale_df_spatial = pop_df.query( "model == 'circles_spatial3D_rtc' or model == 'circles_spatial3D'") plt_df_s = sns.lineplot(x='agent_count', y='s_step_mean', hue='model', style='model', data=scale_df_spatial, ax=ax['p2'], palette=custom_palette, ci="sd") # plt_df_s.ticklabel_format(style='plain', axis='x') # no scientific notation plt_df_s.set(xlabel='N', ylabel='') ax['p2'].set_title(label='B', loc='left', fontweight="bold") ax['p2'].legend().set_visible(False) # Load per simulation step data into data frame (strip any white space) rad_df = pd.read_csv(input_dir / VARIABLE_RADIUS_CSV_FILENAME, sep=',', quotechar='"') rad_df.columns = rad_df.columns.str.strip() rad_df["comm_radius_as_percentage_env_width"] = rad_df[ "comm_radius"] / rad_df["env_width"] * 100 # Plot radius comparison rad_df = rad_df.query( "model == 'circles_spatial3D' or model == 'circles_bruteforce'") plt_df_rad = sns.lineplot(x='comm_radius_as_percentage_env_width', y='s_step_mean', hue='model', data=rad_df, ax=ax['p3'], palette=custom_palette, ci="sd") plt_df_rad.ticklabel_format(style='plain', axis='x') # no scientific notation plt_df_rad.set(xlabel='r as % of W', ylabel='Step time (s)') ax['p3'].set_title(label='C', loc='left', fontweight="bold") ax['p3'].legend().set_visible(False) # plot data volume messages_df = rad_df.query("model == 'circles_spatial3D'") plt_df_rad = sns.lineplot(x='comm_radius_as_percentage_env_width', y='mean_message_count', hue='model', data=messages_df, ax=ax['p4'], palette=custom_palette, ci="sd") plt_df_rad.set(xlabel='r as % of W', ylabel='Messages / step') ax['p4'].set_title(label='D', loc='left', fontweight="bold") ax['p4'].legend().set_visible(False) # Load per simulation step data into data frame (strip any white space) sort_df = pd.read_csv(input_dir / VARIABLE_SORT_PERIOD_CSV_FILENAME, sep=',', quotechar='"') sort_df.columns = sort_df.columns.str.strip() # Plot sort period comparison plot_for_com_radius = 8 max_sort_period_to_plot = 20 sort_df = sort_df.query( "sort_period <= " + str(max_sort_period_to_plot) + " and comm_radius == " + str(plot_for_com_radius) + " and (model == 'circles_spatial3D' or model == 'circles_spatial3D_rtc')" ) plt_df_sort = sns.lineplot(x='sort_period', y='s_step_mean', hue='model', data=sort_df, ax=ax['p5'], palette=custom_palette, ci="sd") plt_df_sort.ticklabel_format(style='plain', axis='x') # no scientific notation plt_df_sort.set(xlabel='Sort period (steps)', ylabel='Step time (s)') ax['p5'].set_title(label='E', loc='left', fontweight="bold") ax['p5'].legend().set_visible(False) # Legend lines_labels = [ax.get_legend_handles_labels() for ax in f.axes] lines, labels = [sum(lol, []) for lol in zip(*lines_labels)] labels = [MODEL_NAME_MAP[l] for l in labels] # Rename labels to provide readable legends unique = {k: v for k, v in zip(labels, lines)} f.legend(unique.values(), unique.keys(), loc='lower right') # Save to image #f.tight_layout() output_dir = pathlib.Path(args.output_dir) f.savefig(output_dir / "paper_figure.png", dpi=args.dpi) f.savefig(output_dir / "paper_figure.pdf", format='pdf', dpi=args.dpi)
lfw_images = data.lfw_subset() for i in range(20): ax[i].imshow(lfw_images[90 + i], cmap=plt.cm.gray) ax[i].axis("off") fig.tight_layout() plt.show() ###################################################################### # Thumbnail image for the gallery # sphinx_gallery_thumbnail_number = -1 from matplotlib.offsetbox import AnchoredText # Create a gridspec with two images in the first and 4 in the second row fig, axd = plt.subplot_mosaic( [["stereo", "stereo", "piv", "piv"], ["lfw0", "lfw1", "lfw2", "lfw3"]], ) axd["stereo"].imshow(cycle_images[0]) axd["stereo"].add_artist( AnchoredText( "Stereo", prop=dict(size=20), frameon=True, borderpad=0, loc="upper left", )) axd["piv"].imshow(vortex_images[0]) axd["piv"].add_artist( AnchoredText( "PIV", prop=dict(size=20), frameon=True,