Python matplotlib.pyplot.sca() Examples
The following are 30
code examples of matplotlib.pyplot.sca().
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.pyplot
, or try the search function
.
Example #1
Source File: environments.py From safe-exploration with MIT License | 6 votes |
def plot_state(self, ax, x=None, color="b", normalize=True): """ Plot the current state or a given state vector Parameters: ----------- ax: Axes Object The axes to plot the state on x: 2x0 array_like[float], optional A state vector of the dynamics Returns ------- ax: Axes Object The axes with the state plotted """ if x is None: x = self.current_state if normalize: x, _ = self.normalize(x) assert len( x) == self.n_s, "x needs to have the same number of states as the dynamics" plt.sca(ax) ax.plot(x[0], x[1], color=color, marker="o", mew=1.2) return ax
Example #2
Source File: produce_heat_maps.py From NeuralTuringMachine with GNU Lesser General Public License v3.0 | 6 votes |
def plot_figures(figures, nrows=1, ncols=1, width_ratios=None): fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows, gridspec_kw={'width_ratios': width_ratios}) for ind, (title, fig) in enumerate(figures): axeslist.ravel()[ind].imshow(fig, cmap='gray', interpolation='nearest') axeslist.ravel()[ind].set_title(title) if TASK != 'Associative Recall' or ind == 0: axeslist.ravel()[ind].set_xlabel('Time ------->') if TASK == 'Associative Recall': plt.sca(axeslist[1]) plt.xticks([0, 1, 2]) plt.sca(axeslist[2]) plt.xticks([0, 1, 2]) if TASK == 'Copy': plt.sca(axeslist[1]) plt.yticks([]) plt.tight_layout()
Example #3
Source File: freesurfer.py From visualqc with Apache License 2.0 | 6 votes |
def plot_contours_in_slice(self, slice_seg, target_axis): """Plots contour around the data in slice (after binarization)""" plt.sca(target_axis) contour_handles = list() for index, label in enumerate(self.unique_labels_display): binary_slice_seg = slice_seg == index if not binary_slice_seg.any(): continue ctr_h = plt.contour(binary_slice_seg, levels=[cfg.contour_level, ], colors=(self.color_for_label[index],), linewidths=cfg.contour_line_width, alpha=self.alpha_seg, zorder=cfg.seg_zorder_freesurfer) contour_handles.append(ctr_h) return contour_handles
Example #4
Source File: plot_functions.py From idea_relations with MIT License | 6 votes |
def plot_sub_joint(self, func, subsample, **kwargs): """Draw a bivariate plot of `x` and `y`. Parameters ---------- func : plotting callable This must take two 1d arrays of data as the first two positional arguments, and it must plot on the "current" axes. kwargs : key, value mappings Keyword argument are passed to the plotting function. Returns ------- self : JointGrid instance Returns `self`. """ if subsample > 0 and subsample < len(self.x): indexes = np.random.choice(range(len(self.x)), subsample, replace=False) plot_x = np.array([self.x[i] for i in indexes]) plot_y = np.array([self.y[i] for i in indexes]) plt.sca(self.ax_joint) func(plot_x, plot_y, **kwargs) else: plt.sca(self.ax_joint) func(self.x, self.y, **kwargs) return self
Example #5
Source File: test_contour.py From neural-network-animation with MIT License | 6 votes |
def test_given_colors_levels_and_extends(): _, axes = plt.subplots(2, 4) data = np.arange(12).reshape(3, 4) colors = ['red', 'yellow', 'pink', 'blue', 'black'] levels = [2, 4, 8, 10] for i, ax in enumerate(axes.flatten()): plt.sca(ax) filled = i % 2 == 0. extend = ['neither', 'min', 'max', 'both'][i // 2] if filled: last_color = -1 if extend in ['min', 'max'] else None plt.contourf(data, colors=colors[:last_color], levels=levels, extend=extend) else: last_level = -1 if extend == 'both' else None plt.contour(data, colors=colors, levels=levels[:last_level], extend=extend) plt.colorbar()
Example #6
Source File: burst_plot.py From FRETBursts with GNU General Public License v2.0 | 6 votes |
def dplot_1ch(d, func, pgrid=True, ax=None, figsize=(9, 4.5), fignum=None, nosuptitle=False, **kwargs): """Plot wrapper for single-spot measurements. Use `dplot` instead.""" global gui_status if ax is None: fig = plt.figure(num=fignum, figsize=figsize) ax = fig.add_subplot(111) else: fig = ax.figure s = d.name if 'bg_mean' in d: s += (' BG=%.1fk' % (d.bg_mean[Ph_sel('all')][0] * 1e-3)) if 'T' in d: s += (u', T=%dμs' % (d.T[0] * 1e6)) if 'mburst' in d: s += (', #bu=%d' % d.num_bursts[0]) if not nosuptitle: ax.set_title(s, fontsize=12) ax.grid(pgrid) plt.sca(ax) gui_status['first_plot_in_figure'] = True func(d, **kwargs) return ax
Example #7
Source File: build_cbct_images.py From pylinac with MIT License | 5 votes |
def identify_images(zip_file): """Interactively identify images from a folder, writing the labels to an array for later training""" with TemporaryZipDirectory(zip_file) as zfiles: filepaths = get_files(zfiles, is_dicom) labels = np.zeros(len(filepaths)) split_val = 25 length = len(filepaths) rounds = int(math.ceil(length / split_val)) for n in range(rounds): fig, axes = plt.subplots(5, 5, figsize=(10, 10)) for axis, (idx, fp) in zip(axes.flatten(), enumerate(filepaths[split_val*n:split_val*(n+1)])): img = load(fp) plt.sca(axis) plt.imshow(img, cmap=plt.cm.Greys) plt.axis('off') plt.title(idx+split_val*n) plt.show() not_done = True while not_done: label = input("Input the HU indices as a number or range. E.g. '66' or '25-47'. Type 'done' when finished:") if label == 'done': not_done = False else: items = label.split('-') if len(items) > 1: labels[int(items[0]):int(items[1])] = 1 else: labels[int(items[0])] = 1 scaled_features = np.zeros((len(filepaths), 10000), dtype=np.float32) for idx, fp in enumerate(filepaths): scaled_features[idx, :] = process_image(fp) dir2write = osp.dirname(zip_file) np.save(osp.join(dir2write, 'images_' + osp.splitext(osp.basename(zip_file))[0]), scaled_features) np.save(osp.join(dir2write, 'labels_' + osp.splitext(osp.basename(zip_file))[0]), labels) os.remove(zip_file)
Example #8
Source File: utils_visualization.py From safe-exploration with MIT License | 5 votes |
def plot_ellipsoid_2D(p, q, ax, n_points = 100, color = "r"): """ Plot an ellipsoid in 2D TODO: Untested! Parameters ---------- p: 3x1 array[float] Center of the ellipsoid q: 3x3 array[float] Shape matrix of the ellipsoid ax: matplotlib.Axes object Ax on which to plot the ellipsoid Returns ------- ax: matplotlib.Axes object The Ax containing the ellipsoid """ plt.sca(ax) r = nLa.cholesky(q).T; #checks spd inside the function t = np.linspace(0, 2*np.pi, n_points); z = [np.cos(t), np.sin(t)]; ellipse = np.dot(r,z) + p; handle, = ax.plot(ellipse[0,:], ellipse[1,:],color) return ax, handle
Example #9
Source File: utils.py From DIAG-NRE with MIT License | 5 votes |
def show_word_scores_heatmap(score_tensor_tup, x_ticks, y_ticks, nrows=1, ncols=1, titles=None, figsize=(8, 8), fontsize=14): def colorbar(mappable): ax = mappable.axes fig = ax.figure divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="1%", pad=0.1) return fig.colorbar(mappable, cax=cax) if not isinstance(score_tensor_tup, tuple): score_tensor_tup = (score_tensor_tup, ) fig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize) for idx, ax in enumerate(axs): score_tensor = score_tensor_tup[idx] img = ax.matshow(score_tensor.numpy()) plt.sca(ax) plt.xticks(range(score_tensor.size(1)), x_ticks, fontsize=fontsize) plt.yticks(range(score_tensor.size(0)), y_ticks, fontsize=fontsize) if titles is not None: plt.title(titles[idx], fontsize=fontsize + 2) colorbar(img) for ax in axs: ax.set_aspect('auto') plt.tight_layout(h_pad=1) plt.show()
Example #10
Source File: process_log.py From SPTM with MIT License | 5 votes |
def add_to_plots(plots, input): FAIL_STEPS = MAX_NUMBER_OF_STEPS_NAVIGATION + 1 environment, mode, result = input steps = [] success_rate = float(sum([value for value, _, _ in result])) / float(len(result)) print environment, mode, success_rate for success, length, _ in result: if success: steps.append(length) else: steps.append(FAIL_STEPS) steps.sort() cumulative = {} for index, step in enumerate(steps): if step < FAIL_STEPS: cumulative[step] = float(index + 1) / float(len(steps)) else: cumulative[step] = success_rate if environment in plots: figure, axes = plots[environment] plt.sca(axes) else: figure, axes = plt.subplots() plots[environment] = figure, axes sorted_cumulative = sorted(cumulative.items()) # print sorted_cumulative x = [0] + [value for value, _ in sorted_cumulative] + [FAIL_STEPS] y = [0] + [value for _, value in sorted_cumulative] + [success_rate] y = [SUCCESS_SCALING * value for value in y] plt.plot(x, y, METHOD_TO_COLOR[mode], linewidth=LINEWIDTH, label=METHOD_TO_LEGEND[mode]) plt.title(ENVIRONMENT_TO_PAPER_TITLE[environment], fontsize=TITLE_FONT) plt.xlabel('Steps', fontsize=AXIS_LABEL_FONT) if ENVIRONMENT_TO_PAPER_TITLE[environment] in ['Test-1', 'Test-5', 'Val-1']: plt.ylabel('Success rate', fontsize=AXIS_LABEL_FONT) plt.axis([0, FAIL_STEPS, 0, 1.0 * SUCCESS_SCALING]) plt.grid(linestyle='dotted') print ENVIRONMENT_TO_PAPER_TITLE[environment] if ENVIRONMENT_TO_PAPER_TITLE[environment] in ['Val-3']: leg = plt.legend(shadow=True, fontsize=LEGEND_FONT, loc='upper left', fancybox=True, framealpha=1.0) for legobj in leg.legendHandles: legobj.set_linewidth(LEGEND_LINE_WIDTH)
Example #11
Source File: environments.py From safe-exploration with MIT License | 5 votes |
def plot_ellipsoid_trajectory(self, p, q, vis_safety_bounds=True, ax=None, color="r"): """ Plot the reachability ellipsoids given in observation space TODO: Need more principled way to transform ellipsoid to internal states Parameters ---------- p: n x n_s array[float] The ellipsoid centers of the trajectory q: n x n_s x n_s ndarray[float] The shape matrices of the trajectory vis_safety_bounds: bool, optional Visualize the safety bounds of the system """ new_ax = False if ax is None: fig = plt.figure() ax = fig.add_subplot(111) new_ax = True plt.sca(ax) n, n_s = np.shape(p) handles = [None] * n for i in range(n): p_i = cas_reshape(p[i, :], (n_s, 1)) + self.p_origin.reshape((n_s, 1)) q_i = cas_reshape(q[i, :], (self.n_s, self.n_s)) ax, handles[i] = plot_ellipsoid_2D(p_i, q_i, ax, color=color) # ax = plot_ellipsoid_2D(p_i,q_i,ax,color = color) if vis_safety_bounds: ax = self.plot_safety_bounds(ax) if new_ax: plt.show() return ax, handles
Example #12
Source File: vmat.py From pylinac with MIT License | 5 votes |
def _plot_analyzed_subimage(self, subimage: str, show: bool=True, ax: plt.Axes=None): """Plot an individual piece of the VMAT analysis. Parameters ---------- subimage : str Specifies which image to plot. show : bool Whether to actually plot the image. ax : matplotlib Axes, None If None (default), creates a new figure to plot to, otherwise plots to the given axes. """ plt.ioff() if ax is None: fig, ax = plt.subplots() # plot DMLC or OPEN image if subimage in (DMLC, OPEN): if subimage == DMLC: img = self.dmlc_image elif subimage == OPEN: img = self.open_image ax.imshow(img, cmap=get_dicom_cmap()) self._draw_segments(ax) plt.sca(ax) plt.axis('off') plt.tight_layout() # plot profile elif subimage == PROFILE: dmlc_prof, open_prof = self._median_profiles((self.dmlc_image, self.open_image)) ax.plot(dmlc_prof.values, label='DMLC') ax.plot(open_prof.values, label='Open') ax.autoscale(axis='x', tight=True) ax.legend(loc=8, fontsize='large') ax.grid() if show: plt.show()
Example #13
Source File: hyper_param.py From geoist with MIT License | 5 votes |
def plot_lcurve(self, ax=None, guides=True): """ Make a plot of the data-misfit x regularization values. The estimated corner value is shown as a blue triangle. Parameters: * ax : matplotlib Axes If not ``None``, will plot the curve on this Axes instance. * guides : True or False Plot vertical and horizontal lines across the corner value. """ if ax is None: ax = mpl.gca() else: mpl.sca(ax) x, y = self.dnorm, self.mnorm if self.loglog: mpl.loglog(x, y, '.-k') else: mpl.plot(x, y, '.-k') if guides: vmin, vmax = ax.get_ybound() mpl.vlines(x[self.corner_], vmin, vmax) vmin, vmax = ax.get_xbound() mpl.hlines(y[self.corner_], vmin, vmax) mpl.plot(x[self.corner_], y[self.corner_], '^b', markersize=10) mpl.xlabel('Data misfit(data norm)') mpl.ylabel('Regularization(model norm)')
Example #14
Source File: test_hinton.py From neupy with MIT License | 5 votes |
def test_simple_hinton(self): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) plt.sca(ax) # To test the case when ax=None weight = np.random.randn(20, 20) plots.hinton(weight, add_legend=True) return fig
Example #15
Source File: helpers.py From gempy with GNU Lesser General Public License v3.0 | 5 votes |
def add_colorbar(im=None, axes=None, cs=None, label = None, aspect=30, location="right", pad_fraction=1, **kwargs): """ Add a colorbar to a plot (im). Args: im: plt imshow label: label of the colorbar axes: cs: Contourset aspect: the higher, the smaller the colorbar is pad_fraction: **kwargs: Returns: A perfect colorbar, no matter the plot. """ if axes is None: axes = im.axes divider = axes_grid1.make_axes_locatable(axes) width = axes_grid1.axes_size.AxesY(axes, aspect=2. / aspect) pad = axes_grid1.axes_size.Fraction(pad_fraction, width) current_ax = plt.gca() cax = divider.append_axes(location, size=width, pad=pad) plt.sca(current_ax) if cs: cbar = axes.figure.colorbar(cs, cax=cax, **kwargs) else: if im is not None: cbar = axes.figure.colorbar(im, cax=cax, **kwargs) cbar.set_label(label) return cbar
Example #16
Source File: posterior_analysis_elisa.py From gempy with GNU Lesser General Public License v3.0 | 5 votes |
def add_colorbar(self, im, aspect=20, pad_fraction=1, **kwargs): """Add a vertical color bar to an image plot. Source: stackoverflow""" divider = axes_grid1.make_axes_locatable(im.axes) width = axes_grid1.axes_size.AxesY(im.axes, aspect=2. / aspect) pad = axes_grid1.axes_size.Fraction(pad_fraction, width) current_ax = plt.gca() cax = divider.append_axes("right", size=width, pad=pad) plt.sca(current_ax) return im.axes.figure.colorbar(im, cax=cax, **kwargs)
Example #17
Source File: plot2d.py From sfs-python with MIT License | 5 votes |
def add_colorbar(im, *, aspect=20, pad=0.5, **kwargs): r"""Add a vertical color bar to a plot. Parameters ---------- im : ScalarMappable The output of `sfs.plot2d.amplitude()`, `sfs.plot2d.level()` or any other `matplotlib.cm.ScalarMappable`. aspect : float, optional Aspect ratio of the colorbar. Strictly speaking, since the colorbar is vertical, it's actually the inverse of the aspect ratio. pad : float, optional Space between image plot and colorbar, as a fraction of the width of the colorbar. .. note:: The *pad* argument of :meth:`matplotlib.figure.Figure.colorbar` has a slightly different meaning ("fraction of original axes")! \**kwargs All further arguments are forwarded to :meth:`matplotlib.figure.Figure.colorbar`. See Also -------- matplotlib.pyplot.colorbar """ ax = im.axes divider = _axes_grid1.make_axes_locatable(ax) width = _axes_grid1.axes_size.AxesY(ax, aspect=1/aspect) pad = _axes_grid1.axes_size.Fraction(pad, width) current_ax = _plt.gca() cax = divider.append_axes("right", size=width, pad=pad) _plt.sca(current_ax) return ax.figure.colorbar(im, cax=cax, orientation='vertical', **kwargs)
Example #18
Source File: plt_ncdata.py From flyingpigeon with Apache License 2.0 | 5 votes |
def add_colorbar(im, aspect=20, pad_fraction=0.5,): """Add a vertical color bar to an image plot.""" from mpl_toolkits import axes_grid1 divider = axes_grid1.make_axes_locatable(im.axes) width = axes_grid1.axes_size.AxesY(im.axes, aspect=1./aspect) pad = axes_grid1.axes_size.Fraction(pad_fraction, width) current_ax = plt.gca() cax = divider.append_axes("right", size=width, pad=pad) plt.sca(current_ax) return im.axes.figure.colorbar(im, cax=cax)
Example #19
Source File: __init__.py From piradar with GNU Affero General Public License v3.0 | 5 votes |
def create_pseudo_random_code(clen=10000, rseed=0, verbose=False): """ Create waveform files for hfradar Juha Vierinen """ Npt = 200 # number of points to plot, just for plotting, arbitrary """ seed is a way of reproducing the random code without having to store all actual codes. the seed can then act as a sort of station_id. """ seed(rseed) """ generate a uniform random phase modulated (complex) signal 'sig". It's single precision floating point for SDR, since DAC is typically <= 16 bits! """ sig = np.exp(1j * 2.0 * np.pi * random(clen)).astype("complex64") if stuffr is not None: stuffr.plot_cts(sig[:Npt]) if verbose and hist is not None: fg, ax = subplots(3, 1) sca(ax[0]) hist(sig.real) # ,50) sca(ax[1]) hist(sig.imag) # hist(random(clen)) return sig
Example #20
Source File: utils_visualization.py From safe-exploration with MIT License | 5 votes |
def plot_ellipsoid_2D(p, q, ax, n_points=100, color="r"): """ Plot an ellipsoid in 2D TODO: Untested! Parameters ---------- p: 3x1 array[float] Center of the ellipsoid q: 3x3 array[float] Shape matrix of the ellipsoid ax: matplotlib.Axes object Ax on which to plot the ellipsoid Returns ------- ax: matplotlib.Axes object The Ax containing the ellipsoid """ plt.sca(ax) r = nLa.cholesky(q).T; # checks spd inside the function t = np.linspace(0, 2 * np.pi, n_points); z = [np.cos(t), np.sin(t)]; ellipse = np.dot(r, z) + p; handle, = ax.plot(ellipse[0, :], ellipse[1, :], color) return ax, handle
Example #21
Source File: Dual-form_Perceptron.py From statistical-learning-methods-note with Apache License 2.0 | 5 votes |
def plotChart(self, costList, misRateList, saveFigPath): ''' 绘制错分率和损失函数值随 epoch 变化的曲线。 :param costList: 训练过程中每个epoch的损失函数列表 :param misRateList: 训练过程中每个epoch的错分率列表 :return: ''' # 导入绘图库 import matplotlib.pyplot as plt # 新建画布 plt.figure('Perceptron Cost and Mis-classification Rate', figsize=(8, 9)) # 设定两个子图和位置关系 ax1 = plt.subplot(211) ax2 = plt.subplot(212) # 选择子图1并绘制损失函数值折线图及相关坐标轴 plt.sca(ax1) plt.plot(xrange(1, len(costList) + 1), costList, '--b*') plt.xlabel('Epoch No.') plt.ylabel('Cost') plt.title('Plot of Cost Function') plt.grid() ax1.legend(u"Cost", loc='best') # 选择子图2并绘制错分率折线图及相关坐标轴 plt.sca(ax2) plt.plot(xrange(1, len(misRateList) + 1), misRateList, '-r*') plt.xlabel('Epoch No.') plt.ylabel('Mis-classification Rate') plt.title('Plot of Mis-classification Rate') plt.grid() ax2.legend(u'Mis-classification Rate', loc='best') # 显示图像并打印和保存 # 需要先保存再绘图否则相当于新建了一张新空白图像然后保存 plt.savefig(saveFigPath) plt.show() ################################### PART3 TEST ######################################## # 例子
Example #22
Source File: adversarial_real_corpus.py From Generative-adversarial-Nets-in-NLP with Apache License 2.0 | 5 votes |
def matplotformat(self, ax, plot_y, plot_name, x_max): plt.sca(ax) plot_x = [i * 5 for i in range(len(plot_y))] plt.xticks(np.linspace(0, x_max, (x_max // 50) + 1, dtype=np.int32)) plt.xlabel('Epochs', fontsize=16) plt.ylabel('NLL by oracle', fontsize=16) plt.title(plot_name) plt.plot(plot_x, plot_y)
Example #23
Source File: Perceptron.py From statistical-learning-methods-note with Apache License 2.0 | 5 votes |
def plotChart(self, costList, misRateList, saveFigPath): ''' 绘制错分率和损失函数值随 epoch 变化的曲线。 :param costList: 训练过程中每个epoch的损失函数列表 :param misRateList: 训练过程中每个epoch的错分率列表 :return: ''' # 导入绘图库 import matplotlib.pyplot as plt # 新建画布 plt.figure('Perceptron Cost and Mis-classification Rate',figsize=(8, 9)) # 设定两个子图和位置关系 ax1 = plt.subplot(211) ax2 = plt.subplot(212) # 选择子图1并绘制损失函数值折线图及相关坐标轴 plt.sca(ax1) plt.plot(xrange(1, len(costList)+1), costList, '--b*') plt.xlabel('Epoch No.') plt.ylabel('Cost') plt.title('Plot of Cost Function') plt.grid() ax1.legend(u"Cost", loc='best') # 选择子图2并绘制错分率折线图及相关坐标轴 plt.sca(ax2) plt.plot(xrange(1, len(misRateList)+1), misRateList, '-r*') plt.xlabel('Epoch No.') plt.ylabel('Mis-classification Rate') plt.title('Plot of Mis-classification Rate') plt.grid() ax2.legend(u'Mis-classification Rate', loc='best') # 显示图像并打印和保存 # 需要先保存再绘图否则相当于新建了一张新空白图像然后保存 plt.savefig(saveFigPath) plt.show() ################################### PART3 TEST ######################################## # 例子
Example #24
Source File: adversarial_poem.py From Generative-adversarial-Nets-in-NLP with Apache License 2.0 | 5 votes |
def matplotformat(self, ax, plot_y, plot_name, x_max): plt.sca(ax) plot_x = [i * 5 for i in range(len(plot_y))] plt.xticks(np.linspace(0, x_max, (x_max // 50) + 1, dtype=np.int32)) plt.xlabel('Epochs', fontsize=16) plt.ylabel('NLL by oracle', fontsize=16) plt.title(plot_name) plt.plot(plot_x, plot_y)
Example #25
Source File: adversarial_ori.py From Generative-adversarial-Nets-in-NLP with Apache License 2.0 | 5 votes |
def matplotformat(self, ax, plot_y, plot_name, x_max): plt.sca(ax) plot_x = [i * 5 for i in range(len(plot_y))] plt.xticks(np.linspace(0, x_max, (x_max // 50) + 1, dtype=np.int32)) plt.xlabel('Epochs', fontsize=16) plt.ylabel('NLL by oracle', fontsize=16) plt.title(plot_name) plt.plot(plot_x, plot_y)
Example #26
Source File: test_ssim.py From DSMnet with Apache License 2.0 | 5 votes |
def implot(im1, im2, im3, im4, im5, im6, im7, im8): m = 4 n = 2 ims = [im1, im2, im3, im4, im5, im6, im7, im8] for i in range(m*n): ax = plt.subplot(m, n, i+1) plt.sca(ax) plt.imshow(ims[i])
Example #27
Source File: adversarial.py From Generative-adversarial-Nets-in-NLP with Apache License 2.0 | 5 votes |
def matplotformat(self, ax, plot_y, plot_name, x_max): plt.sca(ax) plot_x = [i * 5 for i in range(len(plot_y))] plt.xticks(np.linspace(0, x_max, (x_max // 100) + 1, dtype=np.int32)) plt.xlabel('Epochs', fontsize=16) plt.ylabel('NLL by oracle', fontsize=16) plt.title(plot_name) plt.plot(plot_x, plot_y)
Example #28
Source File: adversarial_obama.py From Generative-adversarial-Nets-in-NLP with Apache License 2.0 | 5 votes |
def matplotformat(self, ax, plot_y, plot_name, x_max): plt.sca(ax) plot_x = [i * 5 for i in range(len(plot_y))] plt.xticks(np.linspace(0, x_max, (x_max // 50) + 1, dtype=np.int32)) plt.xlabel('Epochs', fontsize=16) plt.ylabel('NLL by oracle', fontsize=16) plt.title(plot_name) plt.plot(plot_x, plot_y)
Example #29
Source File: data.py From miccai-2016-surgical-activity-rec with Apache License 2.0 | 5 votes |
def visualize_predictions(prediction_seqs, label_seqs, num_classes, fig_width=6.5, fig_height_per_seq=0.5): """ Visualize predictions vs. ground truth. Args: prediction_seqs: A list of int NumPy arrays, each with shape `[duration, 1]`. label_seqs: A list of int NumPy arrays, each with shape `[duration, 1]`. num_classes: An integer. fig_width: A float. Figure width (inches). fig_height_per_seq: A float. Figure height per sequence (inches). Returns: A tuple of the created figure, axes. """ num_seqs = len(label_seqs) max_seq_length = max([seq.shape[0] for seq in label_seqs]) figsize = (fig_width, num_seqs*fig_height_per_seq) fig, axes = plt.subplots(nrows=num_seqs, ncols=1, sharex=True, figsize=figsize) for pred_seq, label_seq, ax in zip(prediction_seqs, label_seqs, axes): plt.sca(ax) plot_label_seq(label_seq, num_classes, 1) plot_label_seq(pred_seq, num_classes, -1) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.xlim(0, max_seq_length) plt.ylim(-2.75, 2.75) plt.tight_layout() return fig, axes
Example #30
Source File: cruise-control.py From python-control with BSD 3-Clause "New" or "Revised" License | 4 votes |
def cruise_plot(sys, t, y, t_hill=5, vref=20, antiwindup=False, linetype='b-', subplots=[None, None]): # Figure out the plot bounds and indices v_min = vref-1.2; v_max = vref+0.5; v_ind = sys.find_output('v') u_min = 0; u_max = 2 if antiwindup else 1; u_ind = sys.find_output('u') # Make sure the upper and lower bounds on v are OK while max(y[v_ind]) > v_max: v_max += 1 while min(y[v_ind]) < v_min: v_min -= 1 # Create arrays for return values subplot_axes = list(subplots) # Velocity profile if subplot_axes[0] is None: subplot_axes[0] = plt.subplot(2, 1, 1) else: plt.sca(subplots[0]) plt.plot(t, y[v_ind], linetype) plt.plot(t, vref*np.ones(t.shape), 'k-') plt.plot([t_hill, t_hill], [v_min, v_max], 'k--') plt.axis([0, t[-1], v_min, v_max]) plt.xlabel('Time $t$ [s]') plt.ylabel('Velocity $v$ [m/s]') # Commanded input profile if subplot_axes[1] is None: subplot_axes[1] = plt.subplot(2, 1, 2) else: plt.sca(subplots[1]) plt.plot(t, y[u_ind], 'r--' if antiwindup else linetype) plt.plot([t_hill, t_hill], [u_min, u_max], 'k--') plt.axis([0, t[-1], u_min, u_max]) plt.xlabel('Time $t$ [s]') plt.ylabel('Throttle $u$') # Applied input profile if antiwindup: # TODO: plot the actual signal from the process? plt.plot(t, np.clip(y[u_ind], 0, 1), linetype) plt.legend(['Commanded', 'Applied'], frameon=False) return subplot_axes # Define the time and input vectors