我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot()。
def plot_counts(counts, gene_type): """Plot expression counts. Return a Figure object""" import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import seaborn as sns import numpy as np fig = plt.figure(figsize=((50 + len(counts) * 5) / 25.4, 210/25.4)) matplotlib.rcParams.update({'font.size': 14}) ax = fig.gca() ax.set_title('{} gene usage'.format(gene_type)) ax.set_xlabel('{} gene'.format(gene_type)) ax.set_ylabel('Count') ax.set_xticks(np.arange(len(counts)) + 0.5) ax.set_xticklabels(counts.index, rotation='vertical') ax.grid(axis='x') ax.set_xlim((-0.25, len(counts))) ax.bar(np.arange(len(counts)), counts['count']) fig.set_tight_layout(True) return fig
def visualize(self, zv, path): self.ax1.clear() self.ax2.clear() z, v = zv if path: np.save(path + '/trajectory.npy', z) z = np.reshape(z, [-1, 2]) self.ax1.hist2d(z[:, 0], z[:, 1], bins=400) self.ax1.set(xlim=self.xlim(), ylim=self.ylim()) v = np.reshape(v, [-1, 2]) self.ax2.hist2d(v[:, 0], v[:, 1], bins=400) self.ax2.set(xlim=self.xlim(), ylim=self.ylim()) if self.display: import matplotlib.pyplot as plt plt.show() plt.pause(0.1) elif path: self.fig.savefig(path + '/visualize.png')
def test_cluster_matrix_average(): import utils import basc import matplotlib.pyplot as plt blobs = generate_blobs() ism = utils.individual_stability_matrix(blobs, 100, 3) y_predict = utils.cluster_timeseries(blobs, 3, similarity_metric = 'correlation', affinity_threshold=0.0) cluster_voxel_scores, K_mask = utils.cluster_matrix_average(ism, y_predict) plt.imshow(K_mask) #%% TEST BASC.PY #Remaining Tests to write: #Join_group_stability #cluster_selection #individual_group_clustered_maps #ndarray_to_vol
def plot_tsne(z_mu, classes, name): import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from sklearn.manifold import TSNE model_tsne = TSNE(n_components=2, random_state=0) z_states = z_mu.data.cpu().numpy() z_embed = model_tsne.fit_transform(z_states) classes = classes.data.cpu().numpy() fig666 = plt.figure() for ic in range(10): ind_vec = np.zeros_like(classes) ind_vec[:, ic] = 1 ind_class = classes[:, ic] == 1 color = plt.cm.Set1(ic) plt.scatter(z_embed[ind_class, 0], z_embed[ind_class, 1], s=10, color=color) plt.title("Latent Variable T-SNE per Class") fig666.savefig('./vae_results/'+str(name)+'_embedding_'+str(ic)+'.png') fig666.savefig('./vae_results/'+str(name)+'_embedding.png')
def save_plot(niters, loss, args): print('Saving training loss-iteration figure...') try: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt name = 'Train-{}_hs-{}_lr-{}_bs-{}'.format(args.train_file, args.hs, args.lr, args.batch_size) plt.title(name) plt.plot(niters, loss) plt.xlabel('iteration') plt.ylabel('loss') plt.savefig(name + '.jpg') print('{} saved!'.format(name + '.jpg')) except ImportError: print('matplotlib not installed and no figure is saved.')
def saveAttention(input_sentence, attentions, outpath): # Set up figure with colorbar import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.ticker as ticker fig = plt.figure(figsize=(24,10), ) ax = fig.add_subplot(111) cax = ax.matshow(attentions.cpu().numpy(), cmap='bone') fig.colorbar(cax) if input_sentence: # Set up axes ax.set_yticklabels([' '] + list(input_sentence) + [' ']) # Show label at every tick ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) plt.tight_layout() plt.savefig(outpath) plt.close('all')
def heatmap(data,ax,xlabel=None,ylabel=None,xticklabels=None,yticklabels=None,title=None,fontsize=12): ''' ??matplotlib.pyplot.pcolor????? ?????(pc,ax)???pc????matplotlib.pyplot.colorbar??????mappable? ''' pc=ax.pcolor(data,cmap=plt.cm.Blues) if xlabel is not None: ax.set_xlabel(xlabel,fontsize=fontsize) if ylabel is not None: ax.set_ylabel(ylabel,fontsize=fontsize) ax.set_xticks(np.arange(data.shape[1])+0.5,minor=False) if xticklabels is not None: ax.set_xticklabels(xticklabels,minor=False,fontsize=fontsize) ax.set_yticks(np.arange(data.shape[0])+0.5,minor=False) if yticklabels is not None: ax.set_yticklabels(yticklabels,minor=False,fontsize=fontsize) if title is not None: ax.set_title(title,fontsize=fontsize) return pc,ax #????X?Y????
def plot_dZ_contours(x, y, dZ, axes=None, dZ_interval=0.5, verbose=False, fig_kwargs={}): r"""For plotting seafloor deformation dZ""" import matplotlib.pyplot as plt dZ_max = max(dZ.max(), -dZ.min()) + dZ_interval clines1 = numpy.arange(dZ_interval, dZ_max, dZ_interval) clines = list(-numpy.flipud(clines1)) + list(clines1) # Create axes if needed if axes is None: fig = plt.figure(**fig_kwargs) axes = fig.add_subplot(111) if len(clines) > 0: if verbose: print "Plotting contour lines at: ",clines axes.contour(x, y, dZ, clines, colors='k') else: print "No contours to plot" return axes
def ensure_pyplot(self): """ Ensures that pyplot has been imported into the embedded IPython shell. Also, makes sure to set the backend appropriately if not set already. """ # We are here if the @figure pseudo decorator was used. Thus, it's # possible that we could be here even if python_mplbackend were set to # `None`. That's also strange and perhaps worthy of raising an # exception, but for now, we just set the backend to 'agg'. if not self._pyplot_imported: if 'matplotlib.backends' not in sys.modules: # Then ipython_matplotlib was set to None but there was a # call to the @figure decorator (and ipython_execlines did # not set a backend). #raise Exception("No backend was set, but @figure was used!") import matplotlib matplotlib.use('agg') # Always import pyplot into embedded shell. self.process_input_line('import matplotlib.pyplot as plt', store_history=False) self._pyplot_imported = True
def activate_matplotlib(backend): """Activate the given backend and set interactive to True.""" import matplotlib matplotlib.interactive(True) # Matplotlib had a bug where even switch_backend could not force # the rcParam to update. This needs to be set *before* the module # magic of switch_backend(). matplotlib.rcParams['backend'] = backend import matplotlib.pyplot matplotlib.pyplot.switch_backend(backend) # This must be imported last in the matplotlib series, after # backend/interactivity choices have been made import matplotlib.pyplot as plt plt.show._needmain = False # We need to detect at runtime whether show() is called by the user. # For this, we wrap it into a decorator which adds a 'called' flag. plt.draw_if_interactive = flag_calls(plt.draw_if_interactive)
def plot_attention(attention_matrix: np.ndarray, source_tokens: List[str], target_tokens: List[str], filename: str): """ Uses matplotlib for creating a visualization of the attention matrix. :param attention_matrix: The attention matrix. :param source_tokens: A list of source tokens. :param target_tokens: A list of target tokens. :param filename: The file to which the attention visualization will be written to. """ import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt assert attention_matrix.shape[0] == len(target_tokens) plt.imshow(attention_matrix.transpose(), interpolation="nearest", cmap="Greys") plt.xlabel("target") plt.ylabel("source") plt.gca().set_xticks([i for i in range(0, len(target_tokens))]) plt.gca().set_yticks([i for i in range(0, len(source_tokens))]) plt.gca().set_xticklabels(target_tokens, rotation='vertical') plt.gca().set_yticklabels(source_tokens) plt.tight_layout() plt.savefig(filename) logger.info("Saved alignment visualization to " + filename)
def _store_as_pdf(self, filename: str, fig_width: float, fig_height: float) -> str: """ Stores the current figure in a pdf file. :param filename: name of the pdf file :param fig_width: width of the figure in cm :param fig_height: height of the figure in cm :warning: modifies the current figure """ import matplotlib.pyplot as plt if not filename.endswith(".pdf"): filename += ".pdf" self.reset_plt() self._latexify(fig_width, fig_height) try: plt.tight_layout() except ValueError: pass self._format_axes(plt.gca()) plt.savefig(filename) self.reset_plt() return os.path.realpath(filename)
def boxplot(self, fig_width: Number, fig_height: Number = None): """ Creates a (horizontal) box plot comparing all single object for a given property. :param fig_width: width of the figure in cm :param fig_height: height of the figure in cm, if None it is calculated from the figure width using the aesthetic ratio """ import seaborn as sns import matplotlib.pyplot as plt self.reset_plt() if fig_height is None: fig_height = self._height_for_width(fig_width) self._fig = plt.figure(figsize=self._fig_size_cm_to_inch(fig_width, fig_height)) df = self.get_data_frame() sns.boxplot(data=df, orient="h")
def run(self, fig): """ Run the exporter on the given figure Parmeters --------- fig : matplotlib.Figure instance The figure to export """ # Calling savefig executes the draw() command, putting elements # in the correct place. fig.savefig(io.BytesIO(), format='png', dpi=fig.dpi) if self.close_mpl: import matplotlib.pyplot as plt plt.close(fig) self.crawl_fig(fig)
def test_viz(): """Test viz.""" import matplotlib.pyplot as plt events = mne.find_events(raw) picks = mne.pick_channels(raw.info['ch_names'], ['MEG 2443', 'MEG 2442', 'MEG 2441']) epochs = mne.Epochs(raw, events, picks=picks, baseline=(None, 0), reject=None, preload=True, event_id={'1': 1, '2': 2, '3': 3, '4': 4}) bad_epochs_idx = [0, 1, 3] n_epochs, n_channels, _ = epochs.get_data().shape fix_log = np.zeros((n_epochs, n_channels)) print(bad_epochs_idx) plot_epochs(epochs, bad_epochs_idx=bad_epochs_idx, fix_log=fix_log) plot_epochs(epochs, bad_epochs_idx=bad_epochs_idx) plot_epochs(epochs, fix_log=fix_log) assert_raises(ValueError, plot_epochs, epochs[:2], bad_epochs_idx=bad_epochs_idx, fix_log=fix_log) plt.close('all')
def set_matplotlib_defaults(plt, style='ggplot'): """Set publication quality defaults for matplotlib. Parameters ---------- plt : instance of matplotlib.pyplot The plt instance. """ import matplotlib matplotlib.style.use(style) fontsize = 17 params = {'axes.labelsize': fontsize + 2, 'text.fontsize': fontsize, 'legend.fontsize': fontsize, 'xtick.labelsize': fontsize, 'ytick.labelsize': fontsize, 'axes.titlesize': fontsize + 2} plt.rcParams.update(params)
def plot(dims, sequence, factorization): import matplotlib matplotlib.use('Agg') # NOQA import matplotlib.pyplot as plt import seaborn as sns sns.set_style("darkgrid") plt.ylabel("Speed improvement") plt.xlabel("Size of embedding layers") plt.title("Fitting speed (1.0 = no change)") plt.xscale('log') plt.plot(dims, 1.0 / sequence, label='Sequence model') plt.plot(dims, 1.0 / factorization, label='Factorization model') plt.legend(loc='lower right') plt.savefig('speed.png') plt.close()
def scoped_mpl_import(): import matplotlib matplotlib.rcParams['backend'] = MPL_BACKEND import matplotlib.pyplot as plt plt.rcParams['toolbar'] = 'None' # mute matplotlib toolbar import seaborn as sns sns.set(style="whitegrid", color_codes=True, font_scale=1.0, rc={'lines.linewidth': 1.0, 'backend': matplotlib.rcParams['backend']}) palette = sns.color_palette("Blues_d") palette.reverse() sns.set_palette(palette) return (matplotlib, plt, sns)
def save_image(real_data, fake_data, filename): assert real_data.shape == fake_data.shape import warnings warnings.filterwarnings("ignore", category=FutureWarning) import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt fig, ax = plt.subplots() plt.scatter(fake_data[:,0], fake_data[:,1], color='red', label='noise (fake, sampled)') plt.scatter(real_data[:,0], real_data[:,1], color='blue', label='hidden (real, inferred)') #plt.axis('equal') plt.legend(loc='upper right', fancybox=True, shadow=True, fontsize=11) plt.grid(True) plt.xlim(-5, 5) plt.ylim(-5, 5) plt.minorticks_on() plt.xlabel('x', fontsize=14, color='black') plt.ylabel('y', fontsize=14, color='black') plt.title('z samples (of first two dimensions)') plt.savefig(filename) plt.close()
def save_image_fake(fake_data, filename): #import warnings #warnings.filterwarnings("ignore", category=FutureWarning) #import numpy as np #import matplotlib #matplotlib.use('Agg') #import matplotlib.pyplot as plt fig, ax = plt.subplots() #plt.scatter(real_data[:,0], real_data[:,1], color='blue', label='real') plt.scatter(fake_data[:,0], fake_data[:,1], color='red', label='fake') plt.axis('equal') #plt.legend(loc='upper right', fancybox=True, shadow=True, fontsize=11) plt.grid(True) plt.xlim(-25, 25) plt.ylim(-25, 25) plt.minorticks_on() plt.xlabel('x', fontsize=14, color='black') plt.ylabel('y', fontsize=14, color='black') #plt.title('Toy dataset') plt.savefig(filename) plt.close()
def save_image_real(real_data, filename): #import warnings #warnings.filterwarnings("ignore", category=FutureWarning) #import numpy as np #import matplotlib #matplotlib.use('Agg') #import matplotlib.pyplot as plt fig, ax = plt.subplots() plt.scatter(real_data[:,0], real_data[:,1], color='blue', label='real') #plt.scatter(fake_data[:,0], fake_data[:,1], color='red', label='fake') plt.axis('equal') #plt.legend(loc='upper right', fancybox=True, shadow=True, fontsize=11) plt.grid(True) plt.xlim(-25, 25) plt.ylim(-25, 25) plt.minorticks_on() plt.xlabel('x', fontsize=14, color='black') plt.ylabel('y', fontsize=14, color='black') #plt.title('Toy dataset') plt.savefig(filename) plt.close()
def save_image(real_data, fake_data, filename): #import warnings #warnings.filterwarnings("ignore", category=FutureWarning) #import numpy as np #import matplotlib #matplotlib.use('Agg') #import matplotlib.pyplot as plt fig, ax = plt.subplots() plt.scatter(real_data[:,0], real_data[:,1], color='blue', label='real') plt.scatter(fake_data[:,0], fake_data[:,1], color='red', label='fake') #plt.axis('equal') plt.legend(loc='upper right', fancybox=True, shadow=True, fontsize=11) plt.grid(True) plt.xlim(-25, 25) plt.ylim(-25, 25) plt.minorticks_on() plt.xlabel('x', fontsize=14, color='black') plt.ylabel('y', fontsize=14, color='black') plt.title('Toy dataset') plt.savefig(filename) plt.close()
def test_idw(self): import numpy as np import matplotlib.pyplot as plt from smt.methods import IDW xt = np.array([0., 1., 2., 3., 4.]) yt = np.array([0., 1., 1.5, 0.5, 1.0]) sm = IDW(p=2) sm.set_training_values(xt, yt) sm.train() num = 100 x = np.linspace(0., 4., num) y = sm.predict_values(x) plt.plot(xt, yt, 'o') plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.legend(['Training data', 'Prediction']) plt.show()
def test_rbf(self): import numpy as np import matplotlib.pyplot as plt from smt.methods import RBF xt = np.array([0., 1., 2., 3., 4.]) yt = np.array([0., 1., 1.5, 0.5, 1.0]) sm = RBF(d0=5) sm.set_training_values(xt, yt) sm.train() num = 100 x = np.linspace(0., 4., num) y = sm.predict_values(x) plt.plot(xt, yt, 'o') plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.legend(['Training data', 'Prediction']) plt.show()
def test_rmtb(self): import numpy as np import matplotlib.pyplot as plt from smt.methods import RMTB xt = np.array([0., 1., 2., 3., 4.]) yt = np.array([0., 1., 1.5, 0.5, 1.0]) xlimits = np.array([[0., 4.]]) sm = RMTB(xlimits=xlimits, order=4, num_ctrl_pts=20, energy_weight=1e-15, regularization_weight=0.) sm.set_training_values(xt, yt) sm.train() num = 100 x = np.linspace(0., 4., num) y = sm.predict_values(x) plt.plot(xt, yt, 'o') plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.legend(['Training data', 'Prediction']) plt.show()
def test_rmtc(self): import numpy as np import matplotlib.pyplot as plt from smt.methods import RMTC xt = np.array([0., 1., 2., 3., 4.]) yt = np.array([0., 1., 1.5, 0.5, 1.0]) xlimits = np.array([[0., 4.]]) sm = RMTC(xlimits=xlimits, num_elements=20, energy_weight=1e-15, regularization_weight=0.) sm.set_training_values(xt, yt) sm.train() num = 100 x = np.linspace(0., 4., num) y = sm.predict_values(x) plt.plot(xt, yt, 'o') plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.legend(['Training data', 'Prediction']) plt.show()
def test_ls(self): import numpy as np import matplotlib.pyplot as plt from smt.methods import LS xt = np.array([0., 1., 2., 3., 4.]) yt = np.array([0., 1., 1.5, 0.5, 1.0]) sm = LS() sm.set_training_values(xt, yt) sm.train() num = 100 x = np.linspace(0., 4., num) y = sm.predict_values(x) plt.plot(xt, yt, 'o') plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.legend(['Training data', 'Prediction']) plt.show()
def test_krg(self): import numpy as np import matplotlib.pyplot as plt from smt.methods import KRG xt = np.array([0., 1., 2., 3., 4.]) yt = np.array([0., 1., 1.5, 0.5, 1.0]) sm = KRG(theta0=[1e-2]) sm.set_training_values(xt, yt) sm.train() num = 100 x = np.linspace(0., 4., num) y = sm.predict_values(x) plt.plot(xt, yt, 'o') plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.legend(['Training data', 'Prediction']) plt.show()
def test_kpls(self): import numpy as np import matplotlib.pyplot as plt from smt.methods import KPLS xt = np.array([0., 1., 2., 3., 4.]) yt = np.array([0., 1., 1.5, 0.5, 1.0]) sm = KPLS(theta0=[1e-2]) sm.set_training_values(xt, yt) sm.train() num = 100 x = np.linspace(0., 4., num) y = sm.predict_values(x) plt.plot(xt, yt, 'o') plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.legend(['Training data', 'Prediction']) plt.show()
def test_kplsk(self): import numpy as np import matplotlib.pyplot as plt from smt.methods import KPLSK xt = np.array([0., 1., 2., 3., 4.]) yt = np.array([0., 1., 1.5, 0.5, 1.0]) sm = KPLSK(theta0=[1e-2]) sm.set_training_values(xt, yt) sm.train() num = 100 x = np.linspace(0., 4., num) y = sm.predict_values(x) yy = sm.predict_derivatives(xt,0) plt.plot(xt, yt, 'o') plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.legend(['Training data', 'Prediction']) plt.show()
def test_random(self): import numpy as np import matplotlib.pyplot as plt from smt.sampling import Random xlimits = np.array([ [0., 4.], [0., 3.], ]) sampling = Random(xlimits=xlimits) num = 50 x = sampling(num) print(x.shape) plt.plot(x[:, 0], x[:, 1], 'o') plt.xlabel('x') plt.ylabel('y') plt.show()
def test_lhs(self): import numpy as np import matplotlib.pyplot as plt from smt.sampling import LHS xlimits = np.array([ [0., 4.], [0., 3.], ]) sampling = LHS(xlimits=xlimits) num = 50 x = sampling(num) print(x.shape) plt.plot(x[:, 0], x[:, 1], 'o') plt.xlabel('x') plt.ylabel('y') plt.show()
def test_full_factorial(self): import numpy as np import matplotlib.pyplot as plt from smt.sampling import FullFactorial xlimits = np.array([ [0., 4.], [0., 3.], ]) sampling = FullFactorial(xlimits=xlimits) num = 50 x = sampling(num) print(x.shape) plt.plot(x[:, 0], x[:, 1], 'o') plt.xlabel('x') plt.ylabel('y') plt.show()
def auto_scatter_outlier(df, plot_cols): import matplotlib.pyplot as plt outlier = [0,0,1,1] # Vector of outlier indicators color = ['DarkBlue','DarkBlue','Red','Red'] # vector of color choices for plot marker = ['x','o','o','x'] # vector of shape choices for plot for col in plot_cols: # loop over the columns fig = plt.figure(figsize=(6, 6)) ax = fig.gca() ## Loop over the zip of the four vectors an subset the data and ## create the plot using the aesthetics provided for o, c, m in zip(outlier, color, marker): temp = df.ix[(df['outlier'] == o)] if temp.shape[0] > 0: temp.plot(kind = 'scatter', x = col, y = 'Marks' , ax = ax, color = c, marker = m) ax.set_title('Scatter plot of marks vs. ' + col) fig.savefig('scatter_' + col + '.png') return plot_cols
def vis_detections(self, im, class_name, gt_boxes, dets): """Visual debugging of detections.""" import matplotlib matplotlib.use('TkAgg') # For Mac OS import matplotlib.pyplot as plt import matplotlib.patches as patches fig, ax = plt.subplots(1) for i in range(np.minimum(10, dets.shape[0])): bbox = dets[i,1:] print(bbox) ax.imshow(np.squeeze(im), cmap="gray") self.plot_patch(ax, patches, bbox, gt=False) plt.title(class_name) self.plot_patch(ax, patches, gt_boxes[0][:4], gt=True) # Display Final composite image plt.show()
def plot_func(cause, effect, seasonal, different, heatmap_func, title): heatmap = numpy.zeros((len(sigma01_vals), len(sd_proc_vals))) eps = eps_vals[seasonal] beta00 = beta00_vals[different] for i, sigma01 in enumerate(sigma01_vals): for j, sd_proc in enumerate(sd_proc_vals): heatmap[i,j] = heatmap_func(cause, effect, eps, beta00, sigma01, sd_proc) print heatmap plot_heatmap(heatmap, 'sd_proc', ['{0:.2g}'.format(x) for x in sd_proc_vals], 'sigma01', ['{0:.2g}'.format(y) for y in sigma01_vals], vmin=0, vmax=1 ) pyplot.title('{}: {} causes {}'.format(title, cause, effect))
def render_systems(params=None): figure = pyplot.figure() axes = figure.add_subplot(111, projection='3d') for currentSystem in database.get_star_log_hashes(from_highest=True): current_position = util.get_cartesian(currentSystem) xs = [current_position[0], current_position[0]] ys = [current_position[1], current_position[1]] zs = [0, current_position[2]] axes.plot(xs, ys, zs) axes.scatter(current_position[0], current_position[1], current_position[2], label=util.get_system_name(currentSystem)) axes.legend() axes.set_title('Systems') axes.set_xlabel('X') axes.set_ylabel('Y') axes.set_zlabel('Z') pyplot.show()
def Plot(obj, ys=None, style='', **options): """Plots a line. Args: obj: sequence of x values, or Series, or anything with Render() ys: sequence of y values style: style string passed along to pyplot.plot options: keyword args passed to pyplot.plot """ options = _UnderrideColor(options) label = getattr(obj, 'label', '_nolegend_') options = _Underride(options, linewidth=3, alpha=0.8, label=label) xs = obj if ys is None: if hasattr(obj, 'Render'): xs, ys = obj.Render() if isinstance(obj, pandas.Series): ys = obj.values xs = obj.index if ys is None: pyplot.plot(xs, style, **options) else: pyplot.plot(xs, ys, style, **options)
def Pcolor(xs, ys, zs, pcolor=True, contour=False, **options): """Makes a pseudocolor plot. xs: ys: zs: pcolor: boolean, whether to make a pseudocolor plot contour: boolean, whether to make a contour plot options: keyword args passed to pyplot.pcolor and/or pyplot.contour """ _Underride(options, linewidth=3, cmap=matplotlib.cm.Blues) X, Y = np.meshgrid(xs, ys) Z = zs x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False) axes = pyplot.gca() axes.xaxis.set_major_formatter(x_formatter) if pcolor: pyplot.pcolormesh(X, Y, Z, **options) if contour: cs = pyplot.contour(X, Y, Z, **options) pyplot.clabel(cs, inline=1, fontsize=10)
def feature_range(maximums, minimums): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt fig, ax = plt.subplots() feature_num = len(maximums) ax.bar(range(feature_num), maximums - minimums, color='r', align='center') ax.set_title('feature scale') plt.xticks(range(feature_num), feature_names) plt.xlim([-1, feature_num]) fig.set_figheight(6) fig.set_figwidth(10) if not os.path.exists('./image'): os.makedirs('./image') fig.savefig('image/ranges.png', dpi=48) plt.close(fig)
def _prepare_trellis(n_cells, max_col): """Aux function """ import matplotlib.pyplot as plt if n_cells == 1: nrow = ncol = 1 elif n_cells <= max_col: nrow, ncol = 1, n_cells else: nrow, ncol = int(math.ceil(n_cells / float(max_col))), max_col fig, axes = plt.subplots(nrow, ncol, figsize=(7.4, 1.5 * nrow + 1)) axes = [axes] if ncol == nrow == 1 else axes.flatten() for ax in axes[n_cells:]: # hide unused axes # XXX: Previously done by ax.set_visible(False), but because of mpl # bug, we just hide the frame. from .topomap import _hide_frame _hide_frame(ax) return fig, axes
def figure_nobar(*args, **kwargs): """Make matplotlib figure with no toolbar""" from matplotlib import rcParams, pyplot as plt old_val = rcParams['toolbar'] try: rcParams['toolbar'] = 'none' fig = plt.figure(*args, **kwargs) # remove button press catchers (for toolbar) cbs = list(fig.canvas.callbacks.callbacks['key_press_event'].keys()) for key in cbs: fig.canvas.callbacks.disconnect(key) except Exception as ex: raise ex finally: rcParams['toolbar'] = old_val return fig
def plot_clicks(self, **kwargs): """Plot the x/y positions stored in self.coords. Parameters ---------- **kwargs : dict Arguments are passed to imshow in displaying the bg image. """ from matplotlib.pyplot import subplots f, ax = subplots() ax.imshow(self.imdata, extent=(0, self.xmax, 0, self.ymax), **kwargs) xlim, ylim = [ax.get_xlim(), ax.get_ylim()] xcoords, ycoords = zip(*self.coords) ax.scatter(xcoords, ycoords, c='r') ann_text = np.arange(len(self.coords)).astype(str) for txt, coord in zip(ann_text, self.coords): ax.annotate(txt, coord, fontsize=20, color='r') ax.set_xlim(xlim) ax.set_ylim(ylim) plt_show()
def plot_clustermap(sequences, title, plotpath, size=300, dpi=200): """ Plot a clustermap of the given sequences size -- Downsample to this many sequences title -- plot title Return the number of clusters. """ logger.info('Clustering %d sequences (downsampled to at most %d)', len(sequences), size) sequences = downsampled(sequences, size) df, linkage, clusters = cluster_sequences(sequences) palette = sns.color_palette([(0.15, 0.15, 0.15)]) palette += sns.color_palette('Spectral', n_colors=max(clusters), desat=0.9) row_colors = [ palette[cluster_id] for cluster_id in clusters ] cm = sns.clustermap(df, row_linkage=linkage, col_linkage=linkage, row_colors=row_colors, linewidths=None, linecolor='none', figsize=(210/25.4, 210/25.4), cmap='Blues', xticklabels=False, yticklabels=False ) if title is not None: cm.fig.suptitle(title) cm.savefig(plotpath, dpi=dpi) # free the memory used by the plot import matplotlib.pyplot as plt plt.close('all') return len(set(clusters))
def _savePlot(self, data, filename): import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt plt.plot(data) plt.savefig(filename)