我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用matplotlib.gridspec.GridSpecFromSubplotSpec()。
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
def _get_axes(self,fig): # TODO is attaching these to the figure a good idea? why not save them # here and reuse them if we recognize the figure being passed in sz = self._fig_sz if hasattr(fig,'_feature_ax') and hasattr(fig,'_stateseq_axs'): return fig._feature_ax, fig._stateseq_axs else: if len(self.states_list) <= 2: gs = GridSpec(sz+len(self.states_list),1) feature_ax = plt.subplot(gs[:sz,:]) stateseq_axs = [plt.subplot(gs[sz+idx]) for idx in range(len(self.states_list))] else: gs = GridSpec(1,2) sgs = GridSpecFromSubplotSpec(len(self.states_list),1,subplot_spec=gs[1]) feature_ax = plt.subplot(gs[0]) stateseq_axs = [plt.subplot(sgs[idx]) for idx in range(len(self.states_list))] for ax in stateseq_axs: ax.grid('off') fig._feature_ax, fig._stateseq_axs = feature_ax, stateseq_axs return feature_ax, stateseq_axs
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
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.
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
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.iteritems(): 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)
def save_image(X_test, X_predict, Y_test ,output_fn, slices=None, nslices=25 ): ''' Writes X_test, X_predict, and Y_test to a single png image. Unless specific slices are given, function will write <nslices> evenly spaced slices. args: X_test -- slice of values input to model X_predict -- slice of predicted values based on X_test Y_test -- slice of predicted values output_fn -- filename of output png file slices -- axial slices to save to png file, None by default nslices -- number of evenly spaced slices to save to png returns: 0 ''' #if no slices are defined by user, set slices to evenly sampled slices along entire number of slices in 3d image volume if slices == None : slices = range(0, X_test.shape[0], int(X_test.shape[0]/nslices) ) #set number of rows and columns in output image. currently, sqrt() means that the image will be a square, but this could be changed if a more vertical orientation is prefered ncol=int(np.sqrt(nslices)) nrow=ncol fig = plt.figure(1 ) #using gridspec because it seems to give a bit more control over the spacing of the images. define a nrow x ncol grid outer_grid = gridspec.GridSpec(nrow, ncol,wspace=0.0, hspace=0.0 ) slice_index=0 #index value for <slices> #iterate over columns and rows: for col in range(ncol): for row in range(nrow) : s=slices[slice_index] i=col*nrow+row #couldn't get inner grid to work properly, so commented out for now. #in theory, should be able to get rid of all white spacing with it #inner_grid = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec=outer_grid[i], wspace=0.0, hspace=0.0) #normalize the three input numpy arrays. normalizing them independently is necessary so that they all have the same scale A=normalize(X_test[s]) B=normalize(X_predict[s]) C=normalize(Y_test[s]) ABC = np.concatenate([A,B,C], axis=1) #use imwshow to display all three images plt.subplot(outer_grid[i] ) plt.imshow(ABC) plt.axis('off') plt.subplots_adjust(hspace=0.0, wspace=0.0) slice_index+=1 outer_grid.tight_layout(fig, pad=0, h_pad=0, w_pad=0 ) plt.savefig(output_fn, dpi=750) return 0
def plot_concept(concept, fig=None, subplot_spec=None, **kwargs): """Plot a concept's cause- and effect-repertoires side-by-side, with some additional metainfo. Examples: >>> # Create an 8-inch by 2-inch figure and plot on it. >>> A = pyphi.compute.concept(sub, ('A',)) >>> fig = matplotlib.pyplot.figure(1, (8, 2)) >>> plot_concept(A, fig=fig, state_fmt='ABC') # use node labels >>> matplotlib.pyplot.show() Args: concept (pyphi.models.Concept): The concept to plot. Keyword args: fig (matplotlib.Figure): A figure on which to plot. If none is provided, a new figure is created and used. Default *None*. subplot_spec (matplotlib.gridspec.GridSpec): A gridspec object indicating where on a figure to plot. If none is provided, the whole figure is used. Default *None*. Any unmatched kwargs are passed to `plot_cause_repertoire` and `plot_effect_repertoire`. """ if fig is None: fig = plt.figure() if subplot_spec is None and fig is not None: # Divide the plotting area into a 1-row by 9-column grid. gs = gridspec.GridSpec(1, 9) else: gs = gridspec.GridSpecFromSubplotSpec(1, 9, subplot_spec=subplot_spec) summary_ax = plt.Subplot(fig, gs[0, 4]) # Use the middle column for metainfo cause_ax = plt.Subplot(fig, gs[0, 0:4]) # Span the leftmost 4 columns effect_ax = plt.Subplot(fig, gs[0, 5:9]) # Span the rightmost 4 columns fig.add_subplot(summary_ax) fig.add_subplot(cause_ax) fig.add_subplot(effect_ax) summary_ax.text(.5, .5, fmt.concept_summary(concept), horizontalalignment='center', verticalalignment='center', multialignment='center') summary_ax.axis('off') plot_cause_repertoire(concept, ax=cause_ax, **kwargs) plot_effect_repertoire(concept, ax=effect_ax, **kwargs) effect_ax.set_yticklabels([]) fig.tight_layout()
def build_figure(self): # plot each markevery case for linear x and y scales figsize = (10, 8) fig = plt.figure(num=1, figsize=figsize) axes_list = [] num_rows = len(self.row_list) outer_grid = gridspec.GridSpec(num_rows, 1) for row in range(num_rows): # outer_ax = fig.add_subplot(outer_grid[row]) # if self.row_list[row][1] != '': # outer_ax.set_title(self.row_list[1]) inner_grid = gridspec.GridSpecFromSubplotSpec(1, self.num_ex, subplot_spec=outer_grid[row], wspace=0.0, hspace=0.0) image_row = self.row_list[row][0] for col in range(self.num_ex): ax = plt.Subplot(fig, inner_grid[col]) ax.set_xticks([]) ax.set_yticks([]) axes_list.append(fig.add_subplot(ax)) if row==0: axes_list[-1].set_title('ex{}'.format(col)) axes_list[-1].imshow(image_row[0][col], interpolation='none') plt.axis('off') fig.tight_layout() plt.show() # initialization function: plot the background of each frame # Set up formatting for the movie files Writer = animation.writers['imagemagick_file'] writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800) # call the animator. blit=True means only re-draw the parts that have changed. anim = animation.FuncAnimation(fig, self.animate, init_func=self.init, frames=13, interval=50, blit=True) anim.save('basic_animation.gif', writer='imagemagick') plt.show()
def plot_pairs_by_layer_semdeprel_schemes2(df, pairs, majs, mfls, figname, fignum, ymin=0, ymax=100, plot_maj=True): fig = plt.figure(fignum) default_size = fig.get_size_inches() fig.set_size_inches( (default_size[0]*2.5, default_size[1]*2.5) ) outer = gridspec.GridSpec(3, 1, wspace=0.2, hspace=0.5) xsubs, ysubs = 3, 2 #f, _ = plt.subplots(ysubs, xsubs) #, sharex=True, sharey=True) #default_size = f.get_size_inches() #f.set_size_inches( (default_size[0]*1.8, default_size[1]*1.8) ) schemes = df.scheme.unique() maj_line, mfl_line = '', '' for s in range(3): inner = gridspec.GridSpecFromSubplotSpec(2, 3, subplot_spec=outer[s], wspace=0.5, hspace=1) for i, ((source, target), maj, mfl) in enumerate(zip(pairs[s], majs[s], mfls[s])): ax = plt.Subplot(fig, inner[i]) df_source_target_scheme = df[(df['source'] == source) & (df['target'] == target) & (df['scheme'] == schemes[s])] accs = get_accs_from_df(df_source_target_scheme) layers = df_source_target_scheme.layer.values hide_xlabel = True if i < (ysubs-1)*xsubs else False hide_ylabel = True if i % xsubs > 0 else False maj_line, mfl_line = plot_pair_by_layer(ax, layers, accs, maj, mfl, pretty_lang_names[source] + u"\u2192" + pretty_lang_names[target], hide_xlabel=hide_xlabel, hide_ylabel=hide_ylabel, ymin=ymin, ymax=ymax, plot_maj=plot_maj, nbins=3, delta_above=False) fig.add_subplot(ax) # hide unused axes #axarr[-1, -1].axis('off') #for ax in f.axes[len(pairs):-1]: # ax.axis('off') # if plot_maj: # f.legend([maj_line, mfl_line], ['maj', 'mfl'], loc='lower left', bbox_to_anchor=(0.8,0.1), markerscale=1.5, fontsize='medium', frameon=True, title='Legend', edgecolor='black', labelspacing=1) # else: # f.legend([mfl_line], ['mfl'], loc='lower left', bbox_to_anchor=(0.8,0.1), markerscale=1.5, fontsize='medium', frameon=True, title='Legend', edgecolor='black', labelspacing=1) #plt.tight_layout() plt.savefig(figname) return fignum + 1
def main(ds): """ Creates an overview plot for the Lyman-Alpha total water content probe (TWC). It calls all plotting functions and sets up axes layout. """ #Setup up axes layout gs=gridspec.GridSpec(2, 1, height_ratios=[1,4]) top_cell=gs[0,0] bottom_cell=gs[1,0] #sets up bottom 4 axes; dp timeseries, twc timeseries, twc status and cloud status gs1=gridspec.GridSpecFromSubplotSpec(4,1, bottom_cell, height_ratios=[1,1,10,10], hspace=0.05) fig=QaQc_Figure().setup() ax_dp_ts=fig.add_subplot(gs1[3]) ax_twc_temperatures_ts=fig.add_subplot(gs1[2], sharex=fig.get_axes()[0]) ax_twc_status=fig.add_subplot(gs1[1], sharex=fig.get_axes()[0]) ax_cloud_ts=fig.add_subplot(gs1[0], sharex=fig.get_axes()[0]) #sets up top 2 axes; ge scatter and wvss2r scatter gs2=gridspec.GridSpecFromSubplotSpec(1,2, top_cell) ax_scatter_ge=fig.add_subplot(gs2[0], aspect='equal') ax_scatter_wvss2r=fig.add_subplot(gs2[1], aspect='equal') set_suptitle(fig, ds, 'QA-Total Water Content Probe') data=get_data(ds, VARIABLE_NAMES) for k in data.keys(): if not 'int' in str(data[k].dtype): data[k][data[k] == -9999.] = np.nan #Call the plotting methods below: plot_dp_timeseries(ax_dp_ts, data) plot_twc_temperatures(ax_twc_temperatures_ts, data) plot_twc_status(ax_twc_status, data) plot_cloud(ax_cloud_ts, data) plot_twc_vs_ge(ax_scatter_ge, data) plot_twc_vs_wvss2f(ax_scatter_wvss2r, data) #adds grey bar showing takeoff/landing and only plots the flight ax=fig.get_axes()[0] zoom_to_flight_duration(ax, data) add_time_buffer(ax) for ax in fig.get_axes()[0:4]: add_takeoff(ax, data) add_landing(ax, data) return fig #plt.close('all') #ds = netCDF4.Dataset('./data/twc_extract_20160215_b943.nc', 'r') #ds=d #fig = main(ds) #fig.savefig('/home/axel/test.png')
def main(ds): """ Creates overview plot for humidity during a single flight """ # Setup up axes layout: 4 axes in one column gs = gridspec.GridSpec(2, 1, height_ratios=[1,4]) top_cell = gs[0,0] bottom_cell = gs[1,0] gs1 = gridspec.GridSpecFromSubplotSpec(3, 1, bottom_cell, height_ratios=[2,5,10], hspace=0.05) fig = QaQc_Figure().setup() fig.add_subplot(gs1[2,:]) fig.add_subplot(gs1[1,:], sharex=fig.get_axes()[0]) fig.add_subplot(gs1[0,:], sharex=fig.get_axes()[0]) gs2=gridspec.GridSpecFromSubplotSpec(1,1, top_cell) fig.add_subplot(gs2[0,:], aspect='equal') set_suptitle(fig, ds, 'QA-Humidity') data = get_data(ds, VARIABLE_NAMES) data['VMR_CR2'][data['VMR_CR2'] < 0] = np.nan # remove unreasonable data tdew_ge=data['TDEW_GE'][:,0].ravel() ps_rvsm=data['PS_RVSM'][:,0].ravel() vp_ge = dp2vp(tdew_ge) vmr_ge = vp2vmr(vp_ge, ps_rvsm) vmr_ge = vmr_ge*1E6 #call the plotting methods below plot_humidity(fig.get_axes()[0], data) plot_alt(fig.get_axes()[1], data) plot_lwc(fig.get_axes()[2], data) plot_humidity_scatter(fig.get_axes()[3], data) # adds grey bar showing takeoff/landing and only plots the flight ax = fig.get_axes()[0] zoom_to_flight_duration(ax, data) add_time_buffer(ax) for ax in fig.get_axes()[:-1]: add_takeoff(ax, data) add_landing(ax, data) fig.canvas.draw() return fig
def main(ds): """ Creates an overview plot for the Rosemount temperature sensors; deiced and non-deiced sensors. It calls all plotting functions and sets up axes layout. """ #Setup up axes layout: 3 axes in one column gs=gridspec.GridSpec(2, 1, height_ratios=[1,4]) top_cell=gs[0,0] bottom_cell=gs[1,0] gs1=gridspec.GridSpecFromSubplotSpec(4,1, bottom_cell, height_ratios=[1,1,10,10], hspace=0.05) fig=QaQc_Figure().setup() ax_tat_ts=fig.add_subplot(gs1[3]) # axes for true air temperature time series ax_iat_ts=fig.add_subplot(gs1[2], sharex=fig.get_axes()[0]) # axes for indicated air temperature time series ax_lwc_ts=fig.add_subplot(gs1[1], sharex=fig.get_axes()[0]) # axes for cloud indicator ax_heater_ts=fig.add_subplot(gs1[0], sharex=fig.get_axes()[0]) # axes for heater indicator gs2=gridspec.GridSpecFromSubplotSpec(1,3, top_cell, hspace=0.15) ax_scatter=fig.add_subplot(gs2[0], aspect='equal') # axes for scatter plot ax_hist=fig.add_subplot(gs2[1]) # axes for histogram ax_ps=fig.add_subplot(gs2[2]) # axes for power spectrum set_suptitle(fig, ds, 'QA-Temperature') data =get_data(ds, VARIABLE_NAMES) for var in ['ITDI', 'NDTI', 'TAT_DI_R', 'TAT_ND_R']: data[var][data[var] <= 0] = np.nan # call all plotting methods plot_tat(ax_tat_ts, data) plot_iat(ax_iat_ts, data) plot_lwc(ax_lwc_ts, data) plot_heater(ax_heater_ts, data) plot_iat_scatter(ax_scatter, data) plot_iat_histogram(ax_hist, data) plot_power_spectrum(ax_ps, data) for ax in fig.get_axes()[0:4]: add_takeoff(ax, data) add_landing(ax, data) ax=fig.get_axes()[0] zoom_to_flight_duration(ax, data) add_time_buffer(ax) return fig #ds = netCDF4.Dataset('D:\\netcdf-test-files\\temperature_qa_extract_20160215_b943.nc', 'r') #plt.close('all') #ds = netCDF4.Dataset('./data/temperature_qa_extract_20160215_b943.nc', 'r') #ds=d #fig = main(ds) #data=get_data(ds, VARIABLE_NAMES) #close('all') #fig=figure() #ax=gca() #plot_power_spectrum(ax, data) #fig.savefig('/home/axel/test.png')