Python matplotlib.gridspec.GridSpecFromSubplotSpec() Examples
The following are 26
code examples of matplotlib.gridspec.GridSpecFromSubplotSpec().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
matplotlib.gridspec
, or try the search function
.
Example #1
Source File: test_constrainedlayout.py From twitter-stock-recommendation with MIT License | 6 votes |
def test_constrained_layout11rat(): 'Test for multiple nested gridspecs with width_ratios' fig = plt.figure(constrained_layout=True, figsize=(10, 3)) gs0 = gridspec.GridSpec(1, 2, figure=fig, width_ratios=[6., 1.]) gsl = gridspec.GridSpecFromSubplotSpec(1, 2, gs0[0]) gsl0 = gridspec.GridSpecFromSubplotSpec(2, 2, gsl[1], height_ratios=[2., 1.]) ax = fig.add_subplot(gs0[1]) example_plot(ax, fontsize=9) axs = [] for gs in gsl0: ax = fig.add_subplot(gs) axs += [ax] pcm = example_pcolor(ax, fontsize=9) fig.colorbar(pcm, ax=axs, shrink=0.6, aspect=70.) ax = fig.add_subplot(gsl[0]) example_plot(ax, fontsize=9)
Example #2
Source File: arrow_plotter.py From visual_dynamics with MIT License | 6 votes |
def __init__(self, fig, gs, labels=None, limits=None): self._fig = fig self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs) self._ax = plt.subplot(self._gs[0]) self._arrow = None if labels: if len(labels) == 2: self._ax.set_xlabel(labels[0]) self._ax.set_ylabel(labels[1]) else: raise ValueError("invalid labels %r" % labels) if limits: if len(limits) == 2 and \ len(limits[0]) == 2 and \ len(limits[1]) == 2: self._ax.set_xlim([limits[0][0], limits[1][0]]) self._ax.set_ylim([limits[0][1], limits[1][1]]) else: raise ValueError("invalid limits %r" % limits) self._fig.canvas.draw() self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
Example #3
Source File: loss_plotter.py From visual_dynamics with MIT License | 6 votes |
def __init__(self, fig, gs, format_strings=None, format_dicts=None, labels=None, xlabel=None, ylabel=None, yscale='linear'): self._fig = fig self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs) self._ax = plt.subplot(self._gs[0]) self._labels = labels or [] self._format_strings = format_strings or [] self._format_dicts = format_dicts or [] self._ax.set_xlabel(xlabel or 'iteration') self._ax.set_ylabel(ylabel or 'loss') self._ax.set_yscale(yscale or 'linear') self._ax.minorticks_on() self._plots = [] self._fig.canvas.draw() self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
Example #4
Source File: test_constrainedlayout.py From twitter-stock-recommendation with MIT License | 6 votes |
def test_constrained_layout11(): 'Test for multiple nested gridspecs ' fig = plt.figure(constrained_layout=True, figsize=(10, 3)) gs0 = gridspec.GridSpec(1, 2, figure=fig) gsl = gridspec.GridSpecFromSubplotSpec(1, 2, gs0[0]) gsl0 = gridspec.GridSpecFromSubplotSpec(2, 2, gsl[1]) ax = fig.add_subplot(gs0[1]) example_plot(ax, fontsize=9) axs = [] for gs in gsl0: ax = fig.add_subplot(gs) axs += [ax] pcm = example_pcolor(ax, fontsize=9) fig.colorbar(pcm, ax=axs, shrink=0.6, aspect=70.) ax = fig.add_subplot(gsl[0]) example_plot(ax, fontsize=9)
Example #5
Source File: mean_plotter.py From visual_dynamics with MIT License | 6 votes |
def __init__(self, fig, gs, label='mean', color='black', alpha=1.0, min_itr=10): self._fig = fig self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs) self._ax = plt.subplot(self._gs[0]) self._label = label self._color = color self._alpha = alpha self._min_itr = min_itr self._ts = np.empty((1, 0)) self._data_mean = np.empty((1, 0)) self._plots_mean = self._ax.plot([], [], '-x', markeredgewidth=1.0, color=self._color, alpha=1.0, label=self._label)[0] self._ax.set_xlim(0-0.5, self._min_itr+0.5) self._ax.set_ylim(0, 1) self._ax.minorticks_on() self._ax.legend(loc='upper right', bbox_to_anchor=(1, 1)) self._init = False self._fig.canvas.draw() self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
Example #6
Source File: test_constrainedlayout.py From twitter-stock-recommendation with MIT License | 6 votes |
def test_constrained_layout6(): 'Test constrained_layout for nested gridspecs' fig = plt.figure(constrained_layout=True) gs = gridspec.GridSpec(1, 2, figure=fig) gsl = gridspec.GridSpecFromSubplotSpec(2, 2, gs[0]) gsr = gridspec.GridSpecFromSubplotSpec(1, 2, gs[1]) axsl = [] for gs in gsl: ax = fig.add_subplot(gs) axsl += [ax] example_plot(ax, fontsize=12) ax.set_xlabel('x-label\nMultiLine') axsr = [] for gs in gsr: ax = fig.add_subplot(gs) axsr += [ax] pcm = example_pcolor(ax, fontsize=12) fig.colorbar(pcm, ax=axsr, pad=0.01, shrink=0.99, location='bottom', ticks=ticker.MaxNLocator(nbins=5))
Example #7
Source File: plot_posterior.py From gempy with GNU Lesser General Public License v3.0 | 6 votes |
def _create_likelihood_axis(self, figure=None, subplot_spec=None, **kwargs): # Making the axes: if figure is None: figsize = kwargs.get('figsize', None) fig, _ = plt.subplots(0, 0, figsize=figsize, constrained_layout=False) else: fig = figure if subplot_spec is None: grid = plt.GridSpec(1, 1, hspace=0.1, wspace=0.1, figure=fig) else: grid = gridspect.GridSpecFromSubplotSpec(1, 1, subplot_spec=subplot_spec) ax_like = fig.add_subplot(grid[0, 0]) ax_like.spines['bottom'].set_position(('data', 0.0)) ax_like.yaxis.tick_right() ax_like.spines['right'].set_position(('axes', 1.03)) ax_like.spines['top'].set_color('none') ax_like.spines['left'].set_color('none') ax_like.set_xlabel('Thickness Obs.') ax_like.set_title('Likelihood') return ax_like
Example #8
Source File: test_constrainedlayout.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_constrained_layout11(): 'Test for multiple nested gridspecs ' fig = plt.figure(constrained_layout=True, figsize=(10, 3)) gs0 = gridspec.GridSpec(1, 2, figure=fig) gsl = gridspec.GridSpecFromSubplotSpec(1, 2, gs0[0]) gsl0 = gridspec.GridSpecFromSubplotSpec(2, 2, gsl[1]) ax = fig.add_subplot(gs0[1]) example_plot(ax, fontsize=9) axs = [] for gs in gsl0: ax = fig.add_subplot(gs) axs += [ax] pcm = example_pcolor(ax, fontsize=9) fig.colorbar(pcm, ax=axs, shrink=0.6, aspect=70.) ax = fig.add_subplot(gsl[0]) example_plot(ax, fontsize=9)
Example #9
Source File: test_constrainedlayout.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_constrained_layout11rat(): 'Test for multiple nested gridspecs with width_ratios' fig = plt.figure(constrained_layout=True, figsize=(10, 3)) gs0 = gridspec.GridSpec(1, 2, figure=fig, width_ratios=[6., 1.]) gsl = gridspec.GridSpecFromSubplotSpec(1, 2, gs0[0]) gsl0 = gridspec.GridSpecFromSubplotSpec(2, 2, gsl[1], height_ratios=[2., 1.]) ax = fig.add_subplot(gs0[1]) example_plot(ax, fontsize=9) axs = [] for gs in gsl0: ax = fig.add_subplot(gs) axs += [ax] pcm = example_pcolor(ax, fontsize=9) fig.colorbar(pcm, ax=axs, shrink=0.6, aspect=70.) ax = fig.add_subplot(gsl[0]) example_plot(ax, fontsize=9)
Example #10
Source File: test_constrainedlayout.py From coffeegrindsize with MIT License | 6 votes |
def test_constrained_layout11rat(): 'Test for multiple nested gridspecs with width_ratios' fig = plt.figure(constrained_layout=True, figsize=(10, 3)) gs0 = gridspec.GridSpec(1, 2, figure=fig, width_ratios=[6., 1.]) gsl = gridspec.GridSpecFromSubplotSpec(1, 2, gs0[0]) gsl0 = gridspec.GridSpecFromSubplotSpec(2, 2, gsl[1], height_ratios=[2., 1.]) ax = fig.add_subplot(gs0[1]) example_plot(ax, fontsize=9) axs = [] for gs in gsl0: ax = fig.add_subplot(gs) axs += [ax] pcm = example_pcolor(ax, fontsize=9) fig.colorbar(pcm, ax=axs, shrink=0.6, aspect=70.) ax = fig.add_subplot(gsl[0]) example_plot(ax, fontsize=9)
Example #11
Source File: test_constrainedlayout.py From coffeegrindsize with MIT License | 6 votes |
def test_constrained_layout11(): 'Test for multiple nested gridspecs ' fig = plt.figure(constrained_layout=True, figsize=(10, 3)) gs0 = gridspec.GridSpec(1, 2, figure=fig) gsl = gridspec.GridSpecFromSubplotSpec(1, 2, gs0[0]) gsl0 = gridspec.GridSpecFromSubplotSpec(2, 2, gsl[1]) ax = fig.add_subplot(gs0[1]) example_plot(ax, fontsize=9) axs = [] for gs in gsl0: ax = fig.add_subplot(gs) axs += [ax] pcm = example_pcolor(ax, fontsize=9) fig.colorbar(pcm, ax=axs, shrink=0.6, aspect=70.) ax = fig.add_subplot(gsl[0]) example_plot(ax, fontsize=9)
Example #12
Source File: spots.py From allesfitter with MIT License | 6 votes |
def setup_grid(): fig = plt.figure(figsize=(8,3.8)) gs0 = gridspec.GridSpec(1, 2) gs00 = gridspec.GridSpecFromSubplotSpec(4, 1, subplot_spec=gs0[0], hspace=0) ax1 = plt.Subplot(fig, gs00[:-1, :]) ax1.set(xlabel='', xticks=[], ylabel='Flux') fig.add_subplot(ax1) ax2 = plt.Subplot(fig, gs00[-1, :]) ax2.set(xlabel='Phase', ylabel='Res.') fig.add_subplot(ax2) gs01 = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs0[1]) ax3 = plt.Subplot(fig, gs01[:, :]) ax3.set(xlabel='Long. (deg)', ylabel='Lat. (deg.)') fig.add_subplot(ax3) plt.tight_layout() return fig, ax1, ax2, ax3
Example #13
Source File: plotBARContour.py From ar-pde-cnn with MIT License | 5 votes |
def plotContourGrid(t, xT, uPred, betas, uTarget): ''' Creates grid of 4 different test cases, plots target, prediction, variance and error for each ''' mpl.rcParams['font.family'] = ['serif'] # default is sans-serif rc('text', usetex=False) fig = plt.figure(figsize=(15, 13), dpi=150) outer = gridspec.GridSpec(2, 2, wspace=0.45, hspace=0.2) # Outer grid for i in range(4): # Inner grid inner = gridspec.GridSpecFromSubplotSpec(4, 1, subplot_spec=outer[i], wspace=0, hspace=0.25) ax = [] for j in range(4): ax0 = plt.Subplot(fig, inner[j]) fig.add_subplot(ax0) ax.append(ax0) # Plot specific test case plotPred(fig, ax, t, xT, uPred[i], betas, uTarget[i]) file_dir = '.' # If directory does not exist create it if not os.path.exists(file_dir): os.makedirs(file_dir) file_name = file_dir+"/burger_BAR_pred" plt.savefig(file_name+".png", bbox_inches='tight') plt.savefig(file_name+".pdf", bbox_inches='tight') plt.show()
Example #14
Source File: test_constrainedlayout.py From twitter-stock-recommendation with MIT License | 5 votes |
def test_constrained_layout7(): 'Test for proper warning if fig not set in GridSpec' with pytest.warns(UserWarning, match='Calling figure.constrained_layout, ' 'but figure not setup to do constrained layout'): fig = plt.figure(constrained_layout=True) gs = gridspec.GridSpec(1, 2) gsl = gridspec.GridSpecFromSubplotSpec(2, 2, gs[0]) gsr = gridspec.GridSpecFromSubplotSpec(1, 2, gs[1]) axsl = [] for gs in gsl: ax = fig.add_subplot(gs) # need to trigger a draw to get warning fig.draw(fig.canvas.get_renderer())
Example #15
Source File: plot_posterior.py From gempy with GNU Lesser General Public License v3.0 | 5 votes |
def _create_joy_axis(self, figure=None, subplot_spec=None, n_samples=None, overlap=.85): if n_samples is None: n_samples = self.n_samples grid = gridspect.GridSpecFromSubplotSpec(n_samples, 1, hspace=-overlap, subplot_spec=subplot_spec) ax_joy = [figure.add_subplot(grid[i, 0]) for i in range(n_samples)] ax_joy[0].set_title('Foo Likelihood') return ax_joy
Example #16
Source File: plot_posterior.py From gempy with GNU Lesser General Public License v3.0 | 5 votes |
def _create_joint_axis(self, figure=None, subplot_spec=None, figsize=None, textsize=None): figsize, ax_labelsize, _, xt_labelsize, linewidth, _ = _scale_fig_size(figsize, textsize) # Instantiate figure and grid if figure is None: fig, _ = plt.subplots(0, 0, figsize=figsize, constrained_layout=True) else: fig = figure if subplot_spec is None: grid = plt.GridSpec(4, 4, hspace=0.1, wspace=0.1, figure=fig) else: grid = gridspect.GridSpecFromSubplotSpec(4, 4, subplot_spec=subplot_spec) # Set up main plot self.axjoin = fig.add_subplot(grid[1:, :-1]) # Set up top KDE self.ax_hist_x = fig.add_subplot(grid[0, :-1], sharex=self.axjoin) self.ax_hist_x.tick_params(labelleft=False, labelbottom=False) # Set up right KDE self.ax_hist_y = fig.add_subplot(grid[1:, -1], sharey=self.axjoin) self.ax_hist_y.tick_params(labelleft=False, labelbottom=False) sns.despine(left=True, bottom=True) return self.axjoin, self.ax_hist_x, self.ax_hist_y
Example #17
Source File: test_constrainedlayout.py From coffeegrindsize with MIT License | 5 votes |
def test_constrained_layout7(): 'Test for proper warning if fig not set in GridSpec' with pytest.warns(UserWarning, match='Calling figure.constrained_layout, ' 'but figure not setup to do constrained layout'): fig = plt.figure(constrained_layout=True) gs = gridspec.GridSpec(1, 2) gsl = gridspec.GridSpecFromSubplotSpec(2, 2, gs[0]) gsr = gridspec.GridSpecFromSubplotSpec(1, 2, gs[1]) axsl = [] for gs in gsl: ax = fig.add_subplot(gs) # need to trigger a draw to get warning fig.draw(fig.canvas.get_renderer())
Example #18
Source File: hrv.py From NeuroKit with MIT License | 5 votes |
def _hrv_plot(peaks, out, sampling_rate=1000): fig = plt.figure(constrained_layout=False) spec = gs.GridSpec(ncols=2, nrows=2, height_ratios=[1, 1], width_ratios=[1, 1]) # Arrange grids ax_distrib = fig.add_subplot(spec[0, :-1]) ax_distrib.set_xlabel("R-R intervals (ms)") ax_distrib.set_title("Distribution of R-R intervals") ax_psd = fig.add_subplot(spec[1, :-1]) spec_within = gs.GridSpecFromSubplotSpec(4, 4, subplot_spec=spec[:, -1], wspace=0.025, hspace=0.05) ax_poincare = fig.add_subplot(spec_within[1:4, 0:3]) ax_marg_x = fig.add_subplot(spec_within[0, 0:3]) ax_marg_x.set_title("Poincaré Plot") ax_marg_y = fig.add_subplot(spec_within[1:4, 3]) # Distribution of RR intervals peaks = _hrv_sanitize_input(peaks) rri = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=False) ax_distrib = summary_plot(rri, ax=ax_distrib) # Poincare plot out.columns = [col.replace("HRV_", "") for col in out.columns] _hrv_nonlinear_show(rri, out, ax=ax_poincare, ax_marg_x=ax_marg_x, ax_marg_y=ax_marg_y) # PSD plot rri, sampling_rate = _hrv_get_rri(peaks, sampling_rate=sampling_rate, interpolate=True) frequency_bands = out[["ULF", "VLF", "LF", "HF", "VHF"]] _hrv_frequency_show(rri, frequency_bands, sampling_rate=sampling_rate, ax=ax_psd)
Example #19
Source File: plotARContour.py From ar-pde-cnn with MIT License | 5 votes |
def plotContourGrid(t, xT, uPred, uTarget): ''' Creates grid of 4 different test cases, plots target, prediction and error for each ''' mpl.rcParams['font.family'] = ['serif'] # default is sans-serif rc('text', usetex=False) fig = plt.figure(figsize=(15, 9), dpi=150) outer = gridspec.GridSpec(2, 2, wspace=0.45, hspace=0.2) # Outer grid for i in range(4): # Inner grid inner = gridspec.GridSpecFromSubplotSpec(3, 1, subplot_spec=outer[i], wspace=0, hspace=0.2) ax = [] for j in range(3): ax0 = plt.Subplot(fig, inner[j]) fig.add_subplot(ax0) ax.append(ax0) # Plot specific test case plotPred(fig, ax, t, xT, uPred[i], uTarget[i]) file_dir = '.' # If directory does not exist create it if not os.path.exists(file_dir): os.makedirs(file_dir) file_name = file_dir+"/burger_AR_pred" plt.savefig(file_name+".png", bbox_inches='tight') plt.savefig(file_name+".pdf", bbox_inches='tight') plt.show()
Example #20
Source File: test_constrainedlayout.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_constrained_layout7(): 'Test for proper warning if fig not set in GridSpec' with pytest.warns(UserWarning, match='Calling figure.constrained_layout, ' 'but figure not setup to do constrained layout'): fig = plt.figure(constrained_layout=True) gs = gridspec.GridSpec(1, 2) gsl = gridspec.GridSpecFromSubplotSpec(2, 2, gs[0]) gsr = gridspec.GridSpecFromSubplotSpec(1, 2, gs[1]) axsl = [] for gs in gsl: ax = fig.add_subplot(gs) # need to trigger a draw to get warning fig.draw(fig.canvas.get_renderer())
Example #21
Source File: _anndata.py From scanpy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _plot_colorbar(mappable, fig, subplot_spec, max_cbar_height: float = 4.0): """ Plots a vertical color bar based on mappable. The height of the colorbar is min(figure-height, max_cmap_height) Parameters ---------- mappable The image to which the colorbar applies. fig The figure object subplot_spec The gridspec subplot. Eg. axs[1,2] max_cbar_height The maximum colorbar height Returns ------- color bar ax """ width, height = fig.get_size_inches() if height > max_cbar_height: # to make the colorbar shorter, the # ax is split and the lower portion is used. axs2 = gridspec.GridSpecFromSubplotSpec( 2, 1, subplot_spec=subplot_spec, height_ratios=[height - max_cbar_height, max_cbar_height], ) heatmap_cbar_ax = fig.add_subplot(axs2[1]) else: heatmap_cbar_ax = fig.add_subplot(subplot_spec) pl.colorbar(mappable, cax=heatmap_cbar_ax) return heatmap_cbar_ax
Example #22
Source File: realtime_plotter.py From visual_dynamics with MIT License | 5 votes |
def __init__(self, fig, gs, time_window=500, labels=None, alphas=None): self._fig = fig self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs) self._ax = plt.subplot(self._gs[0]) self._time_window = time_window self._labels = labels self._alphas = alphas self._init = False if self._labels: self.init(len(self._labels)) self._fig.canvas.draw() self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
Example #23
Source File: textbox.py From visual_dynamics with MIT License | 5 votes |
def __init__(self, fig, gs, log_filename=None, max_display_size=10, border_on=False, bgcolor=mpl.rcParams['figure.facecolor'], bgalpha=1.0, fontsize=12, font_family='sans-serif'): self._fig = fig self._gs = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=gs) self._ax = plt.subplot(self._gs[0]) self._log_filename = log_filename self._text_box = self._ax.text(0.01, 0.95, '', color='black', va='top', ha='left', transform=self._ax.transAxes, fontsize=fontsize, family=font_family) self._text_arr = [] self._max_display_size = max_display_size self._ax.set_xticks([]) self._ax.set_yticks([]) if not border_on: self._ax.spines['top'].set_visible(False) self._ax.spines['right'].set_visible(False) self._ax.spines['bottom'].set_visible(False) self._ax.spines['left'].set_visible(False) self._fig.canvas.draw() self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend self.set_bgcolor(bgcolor, bgalpha) # this must come after fig.canvas.draw() #TODO: Add docstrings here.
Example #24
Source File: plotter_3d.py From visual_dynamics with MIT License | 5 votes |
def __init__(self, fig, gs, num_plots, rows=None, cols=None): if cols is None: cols = int(np.floor(np.sqrt(num_plots))) if rows is None: rows = int(np.ceil(float(num_plots)/cols)) assert num_plots <= rows*cols, 'Too many plots to put into gridspec.' self._fig = fig self._gs = gridspec.GridSpecFromSubplotSpec(8, 1, subplot_spec=gs) self._gs_legend = self._gs[0:1, 0] self._gs_plot = self._gs[1:8, 0] self._ax_legend = plt.subplot(self._gs_legend) self._ax_legend.get_xaxis().set_visible(False) self._ax_legend.get_yaxis().set_visible(False) self._gs_plots = gridspec.GridSpecFromSubplotSpec(rows, cols, subplot_spec=self._gs_plot) self._axarr = [plt.subplot(self._gs_plots[i], projection='3d') for i in range(num_plots)] self._lims = [None for i in range(num_plots)] self._plots = [[] for i in range(num_plots)] for ax in self._axarr: ax.tick_params(pad=0) ax.locator_params(nbins=5) for item in (ax.get_xticklabels() + ax.get_yticklabels() + ax.get_zticklabels()): item.set_fontsize(10) self._fig.canvas.draw() self._fig.canvas.flush_events() # Fixes bug with Qt4Agg backend
Example #25
Source File: action_panel.py From visual_dynamics with MIT License | 5 votes |
def __init__(self, fig, gs, rows, cols, actions_arr): """ Constructs an ActionPanel assuming actions_arr is an array of fully initialized actions. Each action must have: key, name, func. Each action can have: axis_pos, keyboard_binding, ps3_binding. """ assert len(actions_arr) <= rows*cols, 'Too many actions to put into gridspec.' self._fig = fig self._gs = gridspec.GridSpecFromSubplotSpec(rows, cols, subplot_spec=gs) self._axarr = [plt.subplot(self._gs[i]) for i in range(len(actions_arr))] # Read keyboard_bindings and ps3_bindings from config self._actions = {action.key: action for action in actions_arr} for key, action in self._actions.items(): if key in config['keyboard_bindings']: action.kb = config['keyboard_bindings'][key] if key in config['ps3_bindings']: action.pb = config['ps3_bindings'][key] self._buttons = None self._initialize_buttons() self._cid = self._fig.canvas.mpl_connect('key_press_event', self.on_key_press) if ROS_ENABLED: self._ps3_count = 0 rospy.Subscriber(config['ps3_topic'], Joy, self.ps3_callback)
Example #26
Source File: util.py From bayes_nn with MIT License | 4 votes |
def plot_preds(preds, batch): """ Lots of matplotlib magic to plot the predictions :param preds: :param batch: tuple of images, labels :return: """ images, labels = batch if isinstance(preds, list): preds = np.stack(preds) num_samples, num_batch, num_classes = preds.shape ave_preds = np.mean(preds, 0) pred_class = np.argmax(ave_preds, 1) entropy, variance, _, _ = calc_risk(preds) # Do all the plotting for n in range(num_batch): fig = plt.figure(figsize=(10, 8)) outer = gridspec.GridSpec(1, 2, wspace=0.2, hspace=0.2) half = gridspec.GridSpecFromSubplotSpec(4, 4, subplot_spec=outer[0], wspace=0.1, hspace=0.1) colors = get_color(pred_class[n], labels[n]) for num_sample in range(half._ncols * half._nrows): ax = plt.Subplot(fig, half[num_sample]) ax.bar(range(10), preds[num_sample, n], color=colors) ax.set_ylim(0, np.max(preds)) ax.set_xticks([]) ax.set_yticks([]) fig.add_subplot(ax) half = gridspec.GridSpecFromSubplotSpec(3, 1, subplot_spec=outer[1], wspace=0.1, hspace=0.1) ax = plt.Subplot(fig, half[0]) ax.imshow(np.squeeze(images[n])) fig.add_subplot(ax) ax = plt.Subplot(fig, half[1]) ax.bar(range(10), ave_preds[n], color=colors) ax.set_ylim(0, np.max(preds)) ax.set_xticks([]) fig.add_subplot(ax) ax = plt.Subplot(fig, half[2]) t = ax.text(0.5, 0.5, 'Entropy %7.3f \n Std %7.3f' % (entropy[n], variance[n])) t.set_ha('center') fig.add_subplot(ax) # fig.show() plt.savefig('im/plot%i.png' % n)