Python matplotlib.ticker.MultipleLocator() Examples
The following are 30
code examples of matplotlib.ticker.MultipleLocator().
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.ticker
, or try the search function
.
Example #1
Source File: utils.py From seq2seq-summarizer with MIT License | 7 votes |
def show_plot(loss, step=1, val_loss=None, val_metric=None, val_step=1, file_prefix=None): plt.figure() fig, ax = plt.subplots(figsize=(12, 8)) # this locator puts ticks at regular intervals loc = ticker.MultipleLocator(base=0.2) ax.yaxis.set_major_locator(loc) ax.set_ylabel('Loss', color='b') ax.set_xlabel('Batch') plt.plot(range(step, len(loss) * step + 1, step), loss, 'b') if val_loss: plt.plot(range(val_step, len(val_loss) * val_step + 1, val_step), val_loss, 'g') if val_metric: ax2 = ax.twinx() ax2.plot(range(val_step, len(val_metric) * val_step + 1, val_step), val_metric, 'r') ax2.set_ylabel('ROUGE', color='r') if file_prefix: plt.savefig(file_prefix + '.png') plt.close()
Example #2
Source File: utils.py From Dense-CoAttention-Network with MIT License | 6 votes |
def mask_ques(sen, attn, idx2word): """ Put attention weights to each word in sentence. -------------------- Arguments: sen (LongTensor): encoded sentence. attn (FloatTensor): attention weights of each word. idx2word (dict): vocabulary. """ fig, ax = plt.subplots(figsize=(15,15)) ax.matshow(attn, cmap='bone') y = [1] x = [1] + [idx2word[i] for i in sen] ax.set_yticklabels(y) ax.set_xticklabels(x) ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
Example #3
Source File: eval_nmt.py From DL-Seq2Seq with MIT License | 6 votes |
def viz_attn(input_sentence, output_words, attentions): maxi = max(len(input_sentence.split()),len(output_words)) attentions = attentions[:maxi,:maxi] fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(attentions.numpy(), cmap=cm.bone) fig.colorbar(cax) ax.set_xticklabels([''] + input_sentence.split(' ') + ['<EOS>'], rotation=90) ax.set_yticklabels([''] + output_words) ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) plt.show()
Example #4
Source File: joyplot.py From LSDMappingTools with MIT License | 6 votes |
def _setup_axis(ax, x_range, col_name=None, grid=False, x_spacing=None): """ Setup the axis for the joyploy: - add the y label if required (as an ytick) - add y grid if required - make the background transparent - set the xlim according to the x_range - hide the xaxis and the spines """ if col_name is not None: ax.set_yticks([0]) ax.set_yticklabels([col_name]) ax.yaxis.grid(grid) else: ax.yaxis.set_visible(False) ax.patch.set_alpha(0) ax.set_xlim([min(x_range), max(x_range)]) ax.tick_params(axis='both', which='both', length=0, pad=10) if x_spacing is not None: ax.xaxis.set_major_locator(ticker.MultipleLocator(base=x_spacing)) ax.xaxis.set_visible(_DEBUG) ax.set_frame_on(_DEBUG)
Example #5
Source File: plot_confusion_matrix.py From Chinese-Character-and-Calligraphic-Image-Processing with MIT License | 6 votes |
def plotCM(classes, matrix, savname): """classes: a list of class names""" # Normalize by row matrix = matrix.astype(np.float) linesum = matrix.sum(1) linesum = np.dot(linesum.reshape(-1, 1), np.ones((1, matrix.shape[1]))) matrix /= linesum # plot plt.switch_backend('agg') fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(matrix) fig.colorbar(cax) ax.xaxis.set_major_locator(MultipleLocator(1)) ax.yaxis.set_major_locator(MultipleLocator(1)) for i in range(matrix.shape[0]): ax.text(i, i, str('%.2f' % (matrix[i, i] * 100)), va='center', ha='center') ax.set_xticklabels([''] + classes, rotation=90) ax.set_yticklabels([''] + classes) plt.savefig(savname)
Example #6
Source File: energy_stats.py From lmatools with BSD 2-Clause "Simplified" License | 6 votes |
def plot_tot_energy_stats(size_stats, basedate, t_edges, outdir): t_start, t_end = t_edges[:-1], t_edges[1:] starts = np.fromiter( ((s - basedate).total_seconds() for s in t_start), dtype=float ) ends = np.fromiter( ((e - basedate).total_seconds() for e in t_end), dtype=float ) t = (starts+ends) / 2.0 specific_energy = np.abs(size_stats) figure = plt.figure(figsize=(15,10)) ax = figure.add_subplot(111) ax.plot(t,specific_energy,'k-',label='Total Energy',alpha=0.6) plt.legend() # ax.set_xlabel('Time UTC') ax.set_ylabel('Total Energy (J)') for axs in figure.get_axes(): axs.xaxis.set_major_formatter(SecDayFormatter(basedate, axs.xaxis)) axs.set_xlabel('Time (UTC)') axs.xaxis.set_major_locator(MultipleLocator(1800)) axs.xaxis.set_minor_locator(MultipleLocator(1800/2)) return figure # In[6]:
Example #7
Source File: energy_stats.py From lmatools with BSD 2-Clause "Simplified" License | 6 votes |
def plot_energy_stats(size_stats, basedate, t_edges, outdir): t_start, t_end = t_edges[:-1], t_edges[1:] starts = np.fromiter( ((s - basedate).total_seconds() for s in t_start), dtype=float ) ends = np.fromiter( ((e - basedate).total_seconds() for e in t_end), dtype=float ) t = (starts+ends) / 2.0 specific_energy = size_stats figure = plt.figure(figsize=(15,10)) ax = figure.add_subplot(111) ax.plot(t,specific_energy,'k-',label='Specific Energy',alpha=0.6) plt.legend() # ax.set_xlabel('Time UTC') ax.set_ylabel('Specific Energy (J/kg)') for axs in figure.get_axes(): axs.xaxis.set_major_formatter(SecDayFormatter(basedate, axs.xaxis)) axs.set_xlabel('Time (UTC)') axs.xaxis.set_major_locator(MultipleLocator(1800)) axs.xaxis.set_minor_locator(MultipleLocator(1800/2)) return figure
Example #8
Source File: cem.py From visual_dynamics with MIT License | 6 votes |
def visualization_init(self): fig = plt.figure(figsize=(12, 6), frameon=False, tight_layout=True) fig.canvas.set_window_title(self.servoing_pol.predictor.name) gs = gridspec.GridSpec(1, 2) plt.show(block=False) return_plotter = LossPlotter(fig, gs[0], format_dicts=[dict(linewidth=2)] * 2, labels=['mean returns / 10', 'mean discounted returns'], ylabel='returns') return_major_locator = MultipleLocator(1) return_major_formatter = FormatStrFormatter('%d') return_minor_locator = MultipleLocator(1) return_plotter._ax.xaxis.set_major_locator(return_major_locator) return_plotter._ax.xaxis.set_major_formatter(return_major_formatter) return_plotter._ax.xaxis.set_minor_locator(return_minor_locator) learning_plotter = LossPlotter(fig, gs[1], format_dicts=[dict(linewidth=2)] * 2, ylabel='mean evaluation values') return fig, return_plotter, learning_plotter
Example #9
Source File: basic_units.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 6 votes |
def axisinfo(unit, axis): 'return AxisInfo instance for x and unit' if unit == radians: return units.AxisInfo( majloc=ticker.MultipleLocator(base=np.pi/2), majfmt=ticker.FuncFormatter(rad_fn), label=unit.fullname, ) elif unit == degrees: return units.AxisInfo( majloc=ticker.AutoLocator(), majfmt=ticker.FormatStrFormatter(r'$%i^\circ$'), label=unit.fullname, ) elif unit is not None: if hasattr(unit, 'fullname'): return units.AxisInfo(label=unit.fullname) elif hasattr(unit, 'unit'): return units.AxisInfo(label=unit.unit.fullname) return None
Example #10
Source File: modular_metalearning.py From modular-metalearning with MIT License | 6 votes |
def plot_sharing(self): if (self.METRICS['Sharing'] is not None and np.max(self.METRICS['Sharing'])>1e-4 and len(self.METRICS['NumberToWords']) <= 50): #Find ordering aux = list(enumerate(self.METRICS['NumberToWords'])) aux.sort(key = lambda x : x[1]) sorted_order = [_[0] for _ in aux] cax = plt.gca().matshow(np.array( self.METRICS['Sharing'])[sorted_order,:][:,sorted_order] /self.S.usage_normalization) plt.gca().set_xticklabels(['']+sorted(self.METRICS['NumberToWords'])) plt.gca().set_yticklabels(['']+sorted(self.METRICS['NumberToWords'])) plt.gca().xaxis.set_major_locator(ticker.MultipleLocator(1)) plt.gca().yaxis.set_major_locator(ticker.MultipleLocator(1)) if self.store_video: plt.savefig(os.path.join(self.plot_name, 'video/sharing-rate_'+ str(self.step))) plt.gcf().colorbar(cax) plt.savefig(os.path.join(self.plot_name, 'sharing-rate')) plt.clf()
Example #11
Source File: logutils.py From obman_train with GNU General Public License v3.0 | 6 votes |
def plot_logs(logs, score_name="top1", y_max=1, prefix=None, score_type=None): """ Args: score_type (str): label for current curve, [valid|train|aggreg] """ # Plot all losses scores = logs[score_name] if score_type is None: label = prefix + "" else: label = prefix + "_" + score_type.lower() plt.plot(scores, label=label) plt.title(score_name) if score_name == "top1" or score_name == "top1_action": # Set maximum for y axis plt.minorticks_on() x1, x2, _, _ = plt.axis() axes = plt.gca() axes.yaxis.set_minor_locator(MultipleLocator(0.02)) plt.axis((x1, x2, 0, y_max)) plt.grid(b=True, which="minor", color="k", alpha=0.2, linestyle="-") plt.grid(b=True, which="major", color="k", linestyle="-")
Example #12
Source File: train.py From pytorch-in-action with MIT License | 6 votes |
def showAttention(input_sentence, output_words, attentions): try: # 添加绘图中的中文显示 plt.rcParams['font.sans-serif'] = ['STSong'] # 宋体 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 # 使用 colorbar 初始化绘图 fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(attentions.numpy(), cmap='bone') fig.colorbar(cax) # 设置x,y轴信息 ax.set_xticklabels([''] + input_sentence.split(' ') + ['<EOS>'], rotation=90) ax.set_yticklabels([''] + output_words) # 显示标签 ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) plt.show() except Exception as err: logger.error(err)
Example #13
Source File: plot_attention.py From neural-combinatorial-rl-pytorch with MIT License | 6 votes |
def plot_attention(in_seq, out_seq, attentions): """ From http://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html""" # Set up figure with colorbar fig = plt.figure() ax = fig.add_subplot(111) cax = ax.matshow(attentions, cmap='bone') fig.colorbar(cax) # Set up axes ax.set_xticklabels([' '] + [str(x) for x in in_seq], rotation=90) ax.set_yticklabels([' '] + [str(x) for x in out_seq]) # Show label at every tick ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) plt.show()
Example #14
Source File: energy_stats.py From lmatools with BSD 2-Clause "Simplified" License | 5 votes |
def plot(self): fig = plt.figure(figsize=(11,8.5)) starts = np.fromiter( ((s - self.basedate).total_seconds() for s in self.t_start), dtype=float ) ends = np.fromiter( ((e - self.basedate).total_seconds() for e in self.t_end), dtype=float ) t = (starts+ends) / 2.0 window_size = (ends-starts)/60.0 # in minutes moments = np.asarray(self.moments) # N by n_moments ax_energy = fig.add_subplot(2,2,2) ax_energy.plot(t, self.energy/window_size, label='Total energy') ax_energy.legend() ax_count = fig.add_subplot(2,2,1, sharex=ax_energy) #ax_count.plot(t, self.energy_per/window_size, label='$E_T$ flash$^{-1}$ min$^{-1}$ ') ax_count.plot(t, moments[:,0]/window_size, label='Flash rate (min$^{-1}$)') ax_count.legend()#location='upper left') ax_mean = fig.add_subplot(2,2,3, sharex=ax_energy) mean, std, skew, kurt = moments[:,1], moments[:,2], moments[:,3], moments[:,4] sigma = np.sqrt(std) ax_mean.plot(t, mean, label = 'Mean flash size (km)') ax_mean.plot(t, sigma, label = 'Standard deviation (km)') ax_mean.set_ylim(0, 20) ax_mean.legend() # ax_mean.fill_between(t, mean+sigma, mean-sigma, facecolor='blue', alpha=0.5) ax_higher = fig.add_subplot(2,2,4, sharex=ax_energy) ax_higher.plot(t, skew, label='Skewness') ax_higher.plot(t, kurt, label='Kurtosis') ax_higher.set_ylim(-2,10) ax_higher.legend() for ax in fig.get_axes(): ax.xaxis.set_major_formatter(SecDayFormatter(self.basedate, ax.xaxis)) ax.set_xlabel('Time (UTC)') ax.xaxis.set_major_locator(MultipleLocator(3600)) ax.xaxis.set_minor_locator(MultipleLocator(1800)) return fig
Example #15
Source File: energy_stats.py From lmatools with BSD 2-Clause "Simplified" License | 5 votes |
def plot_flash_stat_time_series(basedate, t_edges, stats, major_tick_every=1800): t_start, t_end = t_edges[:-1], t_edges[1:] fig = plt.figure(figsize=(11,8.5)) starts = np.fromiter( ((s - basedate).total_seconds() for s in t_start), dtype=float ) ends = np.fromiter( ((e - basedate).total_seconds() for e in t_end), dtype=float ) t = (starts+ends) / 2.0 window_size = (ends-starts)/60.0 # in minutes ax_energy = fig.add_subplot(2,2,2) ax_energy.plot(t, stats['energy']/window_size, label='Total energy') ax_energy.legend() ax_count = fig.add_subplot(2,2,1, sharex=ax_energy) # ax_count.plot(t, stats['energy_per_flash']/window_size, label='$E_T$ flash$^{-1}$ min$^{-1}$ ') ax_count.plot(t, stats['number']/window_size, label='Flash rate (min$^{-1}$)') ax_count.legend()#location='upper left') ax_mean = fig.add_subplot(2,2,3, sharex=ax_energy) mean, std = stats['mean'], stats['variance'], skew, kurt = stats['skewness'], stats['kurtosis'] sigma = np.sqrt(std) ax_mean.plot(t, mean, label = 'Mean flash size (km)') ax_mean.plot(t, sigma, label = 'Standard deviation (km)') ax_mean.set_ylim(0, 20) ax_mean.legend() # ax_mean.fill_between(t, mean+sigma, mean-sigma, facecolor='blue', alpha=0.5) ax_higher = fig.add_subplot(2,2,4, sharex=ax_energy) ax_higher.plot(t, skew, label='Skewness') ax_higher.plot(t, kurt, label='Kurtosis') ax_higher.set_ylim(-2,10) ax_higher.legend() for ax in fig.get_axes(): ax.xaxis.set_major_formatter(SecDayFormatter(basedate, ax.xaxis)) ax.set_xlabel('Time (UTC)') ax.xaxis.set_major_locator(MultipleLocator(major_tick_every)) ax.xaxis.set_minor_locator(MultipleLocator(major_tick_every/2.0)) return fig
Example #16
Source File: test_ticker.py From coffeegrindsize with MIT License | 5 votes |
def test_basic(self): loc = mticker.MultipleLocator(base=3.147) test_value = np.array([-9.441, -6.294, -3.147, 0., 3.147, 6.294, 9.441, 12.588]) assert_almost_equal(loc.tick_values(-7, 10), test_value)
Example #17
Source File: gru_attention_anki.py From artificial_neural_networks with Apache License 2.0 | 5 votes |
def plot_attention(attention, sentence, predicted_sentence): fig = plt.figure(figsize=(10, 10)) ax = fig.add_subplot(1, 1, 1) ax.matshow(attention, cmap='viridis') fontdict = {'fontsize': 14} ax.set_xticklabels([''] + sentence, fontdict=fontdict, rotation=90) ax.set_yticklabels([''] + predicted_sentence, fontdict=fontdict) ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) plt.show()
Example #18
Source File: calculations_atom_single.py From ARC-Alkali-Rydberg-Calculator with BSD 3-Clause "New" or "Revised" License | 5 votes |
def showPlot(self): """ Shows a level diagram plot """ self.listX = np.array(self.listX) self.ax.set_ylabel("Energy (eV)") self.ax.set_xlim(-0.5 + np.min(self.listX), np.max(self.listX) + 0.5) # X AXIS majorLocator = MultipleLocator(1) self.ax.xaxis.set_major_locator(majorLocator) tickNames = [] for s in self.sList: sNumber = round(2 * s + 1) for l in xrange(self.lFrom, self.lTo + 1): tickNames.append("$^%d %s$" % (sNumber, printStateLetter(l) ) ) tickNum = len(self.ax.get_xticklabels()) self.fig.canvas.draw() self.ax.set_xticks(np.arange(tickNum)) self.ax.set_xticklabels(tickNames) self.ax.set_xlim(-0.5 + np.min(self.listX), np.max(self.listX) + 0.5) self.fig.canvas.mpl_connect('pick_event', self.onpick2) self.state1[0] = -1 # initialise for picking plt.show()
Example #19
Source File: utilities.py From dcase2018_task1 with MIT License | 5 votes |
def plot_confusion_matrix(confusion_matrix, title, labels, values): """Plot confusion matrix. Inputs: confusion_matrix: matrix, (classes_num, classes_num) labels: list of labels values: list of values to be shown in diagonal Ouputs: None """ fig = plt.figure(figsize=(6, 6)) ax = fig.add_subplot(111) cax = ax.matshow(confusion_matrix, cmap=plt.cm.Blues) if labels: ax.set_xticklabels([''] + labels, rotation=90, ha='left') ax.set_yticklabels([''] + labels) ax.xaxis.set_ticks_position('bottom') ax.xaxis.set_major_locator(ticker.MultipleLocator(1)) ax.yaxis.set_major_locator(ticker.MultipleLocator(1)) for n in range(len(values)): plt.text(n - 0.4, n, '{:.2f}'.format(values[n]), color='yellow') plt.title(title) plt.xlabel('Predicted') plt.ylabel('Target') plt.tight_layout() plt.show()
Example #20
Source File: dates.py From twitter-stock-recommendation with MIT License | 5 votes |
def __init__(self, interval=1, tz=None): """ *interval* is the interval between each iteration. For example, if ``interval=2``, mark every second microsecond. """ self._interval = interval self._wrapped_locator = ticker.MultipleLocator(interval) self.tz = tz
Example #21
Source File: plot_Fo_vs_Fc.py From dials with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _plot(self): fig = plt.figure() ax = fig.add_subplot(111) minor_loc = MultipleLocator(10) ax.yaxis.set_minor_locator(minor_loc) ax.xaxis.set_minor_locator(minor_loc) ax.grid(True, which="minor") ax.set_axisbelow(True) ax.set_aspect("equal") ax.set_xlabel(r"$F_c$") ax.set_ylabel(r"$F_o$") ax.scatter(self.fc, self.fobs, s=1, c="indianred") if self.params.max_Fc: ax.set_xlim((0, self.params.max_Fc)) ax.set_ylim((0, self.params.max_Fc)) if self.params.show_y_eq_x: ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c="0.0", linewidth=0.8) if self.model_fit: x = flex.double_range(0, int(ax.get_xlim()[1])) y = self.model_fit(x) ax.plot(x, y, c="0.0", linewidth=0.8) print("Saving plot to {0}".format(self.params.plot_filename)) plt.savefig(self.params.plot_filename)
Example #22
Source File: xview.py From xDeepLearningBook with MIT License | 5 votes |
def showCurves(self, idx, x, ys, line_labels, colors, ax_labels): LINEWIDTH = 1.0 # 线宽 plt.figure(figsize=(8, 4)) # loss ax1 = plt.subplot(121) # 上下窗的上图 for i in range(len(self.line_labels)): line = plt.plot(x[:idx], ys[i][:idx])[0] plt.setp(line, color=colors[i], linewidth=LINEWIDTH, label=line_labels[i]) ax1.xaxis.set_major_locator(MultipleLocator(300)) # 横坐标步长 ax1.yaxis.set_major_locator(MultipleLocator(0.2)) # 纵坐标步长 ax1.set_xlabel(ax_labels[0]) ax1.set_ylabel(ax_labels[1]) plt.grid() plt.legend() # Acc ax2 = plt.subplot(122) # 上下窗的下图 for i in range(len(self.line_labels), len(self.line_labels) * 2): line = plt.plot(x[:idx], ys[i][:idx])[0] plt.setp(line, color=colors[i-len(self.line_labels)], linewidth=LINEWIDTH, label=line_labels[i-len(self.line_labels)]) ax2.xaxis.set_major_locator(MultipleLocator(300)) # 横坐标步长 ax2.yaxis.set_major_locator(MultipleLocator(0.05)) # 纵坐标步长 ax2.set_xlabel(ax_labels[0]) ax2.set_ylabel(ax_labels[2]) plt.grid() plt.legend() plt.show()
Example #23
Source File: xview.py From xDeepLearningBook with MIT License | 5 votes |
def showCurves(self, idx, x, ys, line_labels, colors, ax_labels): lsArr = [':','-'] LINEWIDTH = 2.0 plt.figure(figsize=(8, 4)) # loss ax1 = plt.subplot(211) for i in range(2): line = plt.plot(x[:idx], ys[i][:idx])[0] plt.setp(line, color=colors[i], ls=lsArr[i%2],linewidth=LINEWIDTH, label=line_labels[i]) ax1.xaxis.set_major_locator(MultipleLocator(4000)) ax1.yaxis.set_major_locator(MultipleLocator(0.1)) ax1.set_xlabel(ax_labels[0]) ax1.set_ylabel(ax_labels[1]) plt.grid() plt.legend() # Acc ax2 = plt.subplot(212) for i in range(2, 4): line = plt.plot(x[:idx], ys[i][:idx])[0] plt.setp(line, color=colors[i], ls=lsArr[i%2], linewidth=LINEWIDTH, label=line_labels[i]) ax2.xaxis.set_major_locator(MultipleLocator(4000)) ax2.yaxis.set_major_locator(MultipleLocator(0.02)) ax2.set_xlabel(ax_labels[0]) ax2.set_ylabel(ax_labels[2]) plt.grid() plt.legend() plt.show() plt.close()
Example #24
Source File: tutorial.py From TaskBot with GNU General Public License v3.0 | 5 votes |
def showPlot(points): plt.figure() fig, ax = plt.subplots() # this locator puts ticks at regular intervals loc = ticker.MultipleLocator(base=0.2) ax.yaxis.set_major_locator(loc) plt.plot(points)
Example #25
Source File: chapter3_dnn_L2_mnist.py From xDeepLearningBook with MIT License | 5 votes |
def showCurves(idx ,x,ys, line_labels,colors,ax_labels): LINEWIDTH = 2.0 plt.figure(figsize=(8, 4)) #loss ax1 = plt.subplot(211) for i in range(2): line = plt.plot(x[:idx], ys[i][:idx])[0] plt.setp(line, color=colors[i],linewidth=LINEWIDTH, label=line_labels[i]) ax1.xaxis.set_major_locator(MultipleLocator(4000)) ax1.yaxis.set_major_locator(MultipleLocator(0.1)) ax1.set_xlabel(ax_labels[0]) ax1.set_ylabel(ax_labels[1]) plt.grid() plt.legend() #Acc ax2 = plt.subplot(212) for i in range(2,4): line = plt.plot(x[:idx], ys[i][:idx])[0] plt.setp(line, color=colors[i],linewidth=LINEWIDTH, label=line_labels[i]) ax2.xaxis.set_major_locator(MultipleLocator(4000)) ax2.yaxis.set_major_locator(MultipleLocator(0.02)) ax2.set_xlabel(ax_labels[0]) ax2.set_ylabel(ax_labels[2]) plt.grid() plt.legend() plt.show() # 加载mnist
Example #26
Source File: helper.py From transferable_sent2vec with MIT License | 5 votes |
def save_plot(points, filepath, filetag, epoch): """Generate and save the plot""" path_prefix = os.path.join(filepath, filetag) path = path_prefix + 'epoch_{}.png'.format(epoch) fig, ax = plt.subplots() loc = ticker.MultipleLocator(base=0.2) # this locator puts ticks at regular intervals ax.yaxis.set_major_locator(loc) ax.plot(points) fig.savefig(path) plt.close(fig) # close the figure for f in glob.glob(path_prefix + '*'): if f != path: os.remove(f)
Example #27
Source File: helper.py From transferable_sent2vec with MIT License | 5 votes |
def save_plot(points, filepath, filetag, epoch): """Generate and save the plot""" path_prefix = os.path.join(filepath, filetag) path = path_prefix + 'epoch_{}.png'.format(epoch) fig, ax = plt.subplots() loc = ticker.MultipleLocator(base=0.2) # this locator puts ticks at regular intervals ax.yaxis.set_major_locator(loc) ax.plot(points) fig.savefig(path) plt.close(fig) # close the figure for f in glob.glob(path_prefix + '*'): if f != path: os.remove(f)
Example #28
Source File: helper.py From transferable_sent2vec with MIT License | 5 votes |
def save_plot(points, filepath, filetag, epoch): """Generate and save the plot""" path_prefix = os.path.join(filepath, filetag) path = path_prefix + 'epoch_{}.png'.format(epoch) fig, ax = plt.subplots() loc = ticker.MultipleLocator(base=0.2) # this locator puts ticks at regular intervals ax.yaxis.set_major_locator(loc) ax.plot(points) fig.savefig(path) plt.close(fig) # close the figure for f in glob.glob(path_prefix + '*'): if f != path: os.remove(f)
Example #29
Source File: runme.py From dcase2017_task4_cvssp with MIT License | 5 votes |
def sed_visualize(): import matplotlib.pyplot as plt import matplotlib.ticker as ticker sed_prob_mat_list_path = 'data/sed_prob_mat_list.csv.gz' (na_list, pd_prob_mat_list, gt_digit_mat_list) = visualize.sed_visualize( sed_prob_mat_list_path=sed_prob_mat_list_path, strong_gt_csv=strong_gt_csv, lbs=lbs, step_sec=step_sec, max_len=max_len) for n in xrange(len(na_list)): na = na_list[n] pd_prob_mat = pd_prob_mat_list[n] gt_digit_mat = gt_digit_mat_list[n] fig, axs = plt.subplots(3, 1, sharex=True) axs[0].set_title(na + "\nYou may plot spectrogram here yourself. ") # axs[0].matshow(x.T, origin='lower', aspect='auto') # load & plot spectrogram here. axs[1].set_title("Prediction") axs[1].matshow(pd_prob_mat.T, origin='lower', aspect='auto', vmin=0., vmax=1.) axs[1].set_yticklabels([''] + lbs) axs[1].yaxis.set_major_locator(ticker.MultipleLocator(1)) axs[1].yaxis.grid(color='w', linestyle='solid', linewidth=0.3) axs[2].set_title("Ground truth") axs[2].matshow(gt_digit_mat.T, origin='lower', aspect='auto', vmin=0., vmax=1.) axs[2].set_yticklabels([''] + lbs) axs[2].yaxis.set_major_locator(ticker.MultipleLocator(1)) axs[2].yaxis.grid(color='w', linestyle='solid', linewidth=0.3) plt.show() ### main
Example #30
Source File: test_ticker.py From coffeegrindsize with MIT License | 5 votes |
def test_view_limits_round_numbers(self): """ Test that everything works properly with 'round_numbers' for auto limit. """ with matplotlib.rc_context({'axes.autolimit_mode': 'round_numbers'}): loc = mticker.MultipleLocator(base=3.147) assert_almost_equal(loc.view_limits(-4, 4), (-6.294, 6.294))