本文整理汇总了Python中matplotlib.ticker.MultipleLocator方法的典型用法代码示例。如果您正苦于以下问题:Python ticker.MultipleLocator方法的具体用法?Python ticker.MultipleLocator怎么用?Python ticker.MultipleLocator使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.ticker
的用法示例。
在下文中一共展示了ticker.MultipleLocator方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plotCM
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
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)
开发者ID:MingtaoGuo,项目名称:Chinese-Character-and-Calligraphic-Image-Processing,代码行数:22,代码来源:plot_confusion_matrix.py
示例2: _setup_axis
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
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)
示例3: visualization_init
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
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
示例4: show_plot
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
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()
示例5: axisinfo
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
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
示例6: plot_logs
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
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="-")
示例7: showAttention
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
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)
示例8: plot_attention
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
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()
示例9: mask_ques
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
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))
示例10: plot_sharing
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
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()
示例11: plot_energy_stats
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
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
示例12: plot_tot_energy_stats
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
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]:
示例13: viz_attn
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
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()
示例14: showPlot
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
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)
示例15: reset_axis
# 需要导入模块: from matplotlib import ticker [as 别名]
# 或者: from matplotlib.ticker import MultipleLocator [as 别名]
def reset_axis(axes):
plt.cla()
axes.set_xlim(0, image_width)
axes.xaxis.set_major_locator(MultipleLocator(4))
axes.xaxis.set_minor_locator(MultipleLocator(1))
axes.xaxis.grid(True, which='minor')
axes.set_ylim(-image_height, 0)
axes.yaxis.set_major_locator(MultipleLocator(4))
axes.yaxis.set_minor_locator(MultipleLocator(1))
axes.yaxis.grid(True, which='minor')