本文整理汇总了Python中matplotlib.pyplot.ticklabel_format方法的典型用法代码示例。如果您正苦于以下问题:Python pyplot.ticklabel_format方法的具体用法?Python pyplot.ticklabel_format怎么用?Python pyplot.ticklabel_format使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.pyplot
的用法示例。
在下文中一共展示了pyplot.ticklabel_format方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: subfig_evo_el_energy
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def subfig_evo_el_energy(ax_energy, g, legend, **kwargs):
number_ticks = 6
el_energy = g.el_energy * m_e_MeV
el_energy_av = int(np.mean(el_energy))
ax_energy.plot(g.z, np.average(el_energy - el_energy_av, axis=0), 'b-', linewidth=1.5)
ax_energy.set_ylabel('E + ' + str(el_energy_av) + '[MeV]')
ax_energy.ticklabel_format(axis='y', style='sci', scilimits=(-3, 3), useOffset=False)
ax_energy.grid(kwargs.get('grid', True))
ax_spread = ax_energy.twinx()
ax_spread.plot(g.z, np.average(g.el_e_spread * m_e_GeV * 1000, weights=g.I, axis=0), 'm--', g.z,
np.amax(g.el_e_spread * m_e_GeV * 1000, axis=0), 'r--', linewidth=1.5)
ax_spread.set_ylabel(r'$\sigma_E$ [MeV]')
ax_spread.grid(False)
ax_spread.set_ylim(ymin=0)
ax_energy.yaxis.major.locator.set_params(nbins=number_ticks)
ax_spread.yaxis.major.locator.set_params(nbins=number_ticks)
ax_energy.tick_params(axis='y', which='both', colors='b')
ax_energy.yaxis.label.set_color('b')
ax_spread.tick_params(axis='y', which='both', colors='r')
ax_spread.yaxis.label.set_color('r')
示例2: plot_clustering_3d
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def plot_clustering_3d(obj, data_local, data_global, filename):
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
colors = get_colors(len(obj.c_to_ind))
ax.plot(*zip(*data_global), marker='o', color='k', ls='', ms=4., mew=1.0, alpha=0.4, mec='none')
for i,c in enumerate(obj.c_to_ind):
ax.plot(*zip(*data_local[obj.c_to_ind[c]]), marker='o', color=colors[i], ls='', ms=4., mew=1.0, alpha=0.8, mec='none')
plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
ax.view_init(*params.ANGLE)
#plt.grid(True)
#ax.set_axis_bgcolor('grey')
fig.savefig(filename, format='png')
plt.close()
示例3: plot_clustering
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def plot_clustering(obj, data, filename, axis_str=('', ''), tit_str_add='', anot=None):
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111)
colors = get_colors(len(obj.c_to_ind))
for i,c in enumerate(obj.c_to_ind):
plt.plot(*zip(*data[obj.c_to_ind[c]]), marker='o', color=colors[i], ls='', ms=4., mew=1.0, alpha=0.8, mec='none')
plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0))
#plt.grid(True)
#ax.set_axis_bgcolor('grey')
plt.xlabel(axis_str[0])
plt.ylabel(axis_str[1])
fig.savefig(filename, format='png')
plt.close()
示例4: plot_from_summaries
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def plot_from_summaries(summaries_path, title=None, samples_per_update=512, updates_per_log=100):
acc = EventAccumulator(summaries_path)
acc.Reload()
rews_mean = np.array([s[2] for s in acc.Scalars('Rewards/Mean')])
rews_std = np.array([s[2] for s in acc.Scalars('Rewards/Std')])
x = samples_per_update * updates_per_log * np.arange(0, len(rews_mean))
if not title:
title = summaries_path.split('/')[-1].split('_')[0]
plt.plot(x, rews_mean)
plt.fill_between(x, rews_mean - rews_std, rews_mean + rews_std, alpha=0.2)
plt.xlabel('Samples')
plt.ylabel('Episode Rewards')
plt.title(title)
plt.xlim([0, x[-1]+1])
plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
示例5: make_chart_misleading_y_axis
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def make_chart_misleading_y_axis(plt, mislead=True):
mentions = [500, 505]
years = [2013, 2014]
plt.bar([2012.6, 2013.6], mentions, 0.8)
plt.xticks(years)
plt.ylabel("# of times I heard someone say 'data science'")
# if you don't do this, matplotlib will label the x-axis 0, 1
# and then add a +2.013e3 off in the corner (bad matplotlib!)
plt.ticklabel_format(useOffset=False)
if mislead:
# misleading y-axis only shows the part above 500
plt.axis([2012.5,2014.5,499,506])
plt.title("Look at the 'Huge' Increase!")
else:
plt.axis([2012.5,2014.5,0,550])
plt.title("Not So Huge Anymore.")
plt.show()
示例6: make_chart_misleading_y_axis
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def make_chart_misleading_y_axis(mislead=True):
mentions = [500, 505]
years = [2013, 2014]
plt.bar([2012.6, 2013.6], mentions, 0.8)
plt.xticks(years)
plt.ylabel("# of times I heard someone say 'data science'")
# if you don't do this, matplotlib will label the x-axis 0, 1
# and then add a +2.013e3 off in the corner (bad matplotlib!)
plt.ticklabel_format(useOffset=False)
if mislead:
# misleading y-axis only shows the part above 500
plt.axis([2012.5,2014.5,499,506])
plt.title("Look at the 'Huge' Increase!")
else:
plt.axis([2012.5,2014.5,0,550])
plt.title("Not So Huge Anymore.")
plt.show()
示例7: visualize
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def visualize(file_path):
entries = []
with open(file_path) as f:
entries = [json.loads(line) for line in f.readlines() if line.strip()]
if not entries:
print('There is no data in file {}'.format(file_path))
return
pdf = backend_pdf.PdfPages("process_info.pdf")
idx = 0
names = [name for name in entries[0].keys() if name != 'time']
times = [entry['time'] for entry in entries]
for name in names:
values = [entry[name] for entry in entries]
fig = plt.figure()
ax = plt.gca()
ax.yaxis.set_major_formatter(tick.ScalarFormatter(useMathText=True))
plt.ticklabel_format(style='sci', axis='y', scilimits=(-2,3))
plt.plot(times, values, colors[idx % len(colors)], marker='x', label=name)
plt.xlabel('Time (sec)')
plt.ylabel(name)
plt.ylim(ymin=0)
plt.legend(loc = 'upper left')
pdf.savefig(fig)
idx += 1
plt.show()
pdf.close()
print('Generated process_info.pdf from {}'.format(file_path))
示例8: subfig_z_energy_espread_bunching
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def subfig_z_energy_espread_bunching(ax_energy, g, zi=None, x_units='um', legend=False, *args, **kwargs):
ax_energy.clear()
number_ticks = 6
if x_units == 'um':
ax_energy.set_xlabel(r's [$\mu$m]')
x = g.t * speed_of_light * 1.0e-15 * 1e6
elif x_units == 'fs':
ax_energy.set_xlabel(r't [fs]')
x = g.t
else:
raise ValueError('Unknown parameter x_units (should be um or fs)')
if zi == None:
zi = -1
ax_energy.plot(x, g.el_energy[:, zi] * m_e_GeV, 'b-', x, (g.el_energy[:, zi] + g.el_e_spread[:, zi]) * m_e_GeV,
'r--', x, (g.el_energy[:, zi] - g.el_e_spread[:, zi]) * m_e_GeV, 'r--')
ax_energy.set_ylabel(r'$E\pm\sigma_E$ [GeV]')
# ax_energy.ticklabel_format(axis='y', style='sci', scilimits=(-3, 3), useOffset=False)
ax_energy.ticklabel_format(useOffset=False, style='plain')
ax_energy.grid(kwargs.get('grid', True))
# plt.yticks(plt.yticks()[0][0:-1])
ax_bunching = ax_energy.twinx()
ax_bunching.plot(x, g.bunching[:, zi], 'grey', linewidth=0.5)
ax_bunching.set_ylabel('Bunching')
ax_bunching.set_ylim(ymin=0)
ax_bunching.grid(False)
ax_energy.yaxis.major.locator.set_params(nbins=number_ticks)
ax_bunching.yaxis.major.locator.set_params(nbins=number_ticks)
ax_energy.tick_params(axis='y', which='both', colors='b')
ax_energy.yaxis.label.set_color('b')
ax_bunching.tick_params(axis='y', which='both', colors='grey')
ax_bunching.yaxis.label.set_color('grey')
ax_energy.set_xlim([x[0], x[-1]])
示例9: subfig_z_energy_espread
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def subfig_z_energy_espread(ax_energy, g, zi=None, x_units='um', legend=False, *args, **kwargs):
ax_energy.clear()
number_ticks = 6
if x_units == 'um':
ax_energy.set_xlabel(r's [$\mu$m]')
x = g.t * speed_of_light * 1.0e-15 * 1e6
elif x_units == 'fs':
ax_energy.set_xlabel(r't [fs]')
x = g.t
else:
raise ValueError('Unknown parameter x_units (should be um or fs)')
if zi == None:
zi = -1
ax_energy.plot(x, g.el_energy[:, zi] * m_e_GeV, 'b-', x, (g.el_energy[:, zi] + g.el_e_spread[:, zi]) * m_e_GeV,
'r--', x, (g.el_energy[:, zi] - g.el_e_spread[:, zi]) * m_e_GeV, 'r--')
ax_energy.set_ylabel(r'$E\pm\sigma_E$ [GeV]')
# ax_energy.ticklabel_format(axis='y', style='sci', scilimits=(-3, 3), useOffset=False)
ax_energy.ticklabel_format(useOffset=False, style='plain')
ax_energy.grid(kwargs.get('grid', True))
# plt.yticks(plt.yticks()[0][0:-1])
ax_energy.yaxis.major.locator.set_params(nbins=number_ticks)
ax_energy.tick_params(axis='y', which='both', colors='b')
ax_energy.yaxis.label.set_color('b')
ax_energy.set_xlim([x[0], x[-1]])
示例10: plot_data
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def plot_data(
data,
xaxis="Epoch",
value="AverageEpRet",
condition="Condition1",
smooth=1,
**kwargs
):
if smooth > 1:
"""
smooth data with moving window average.
that is,
smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k])
where the "smooth" param is width of that window (2k+1)
"""
y = np.ones(smooth)
for datum in data:
x = np.asarray(datum[value])
z = np.ones(len(x))
smoothed_x = np.convolve(x, y, "same") / np.convolve(z, y, "same")
datum[value] = smoothed_x
if isinstance(data, list):
data = pd.concat(data, ignore_index=True)
sns.set(style="darkgrid", font_scale=1.5)
sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci="sd", **kwargs)
plt.legend(
loc="upper center", ncol=3, handlelength=1, borderaxespad=0.0, prop={"size": 13}
).set_draggable(True)
xscale = np.max(np.asarray(data[xaxis])) > 5e3
if xscale:
# Just some formatting niceness: x-axis scale in scientific notation if max x is large
plt.ticklabel_format(style="sci", axis="x", scilimits=(0, 0))
plt.tight_layout(pad=0.5)
示例11: plot_convergence_curve
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def plot_convergence_curve(data, info, dirname):
# plot the convergence curve
eps = 1e-6
# compute the best pobj over all methods
best_pobj = np.min([np.min(r['pobj']) for _, r in data])
fig = plt.figure("convergence", figsize=(12, 12))
plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
color_cycle = itertools.cycle(COLORS)
for (args, res), color in zip(data, color_cycle):
times = list(np.cumsum(res['times']))
plt.loglog(
times, (res['pobj'] - best_pobj) / best_pobj + eps, '.-',
label=get_label(info['grid_key'], args), color=color,
linewidth=2)
plt.xlabel('Time (s)', fontsize=24)
plt.ylabel('Objective value', fontsize=24)
ncol = int(np.ceil(len(data) / 10))
plt.legend(ncol=ncol, fontsize=24)
plt.gca().tick_params(axis='x', which='both', bottom=False, top=False)
plt.gca().tick_params(axis='y', which='both', left=False, right=False)
plt.tight_layout()
plt.grid(True)
figname = "{}/convergence.png".format(dirname)
fig.savefig(figname, dpi=150)
示例12: print_save_plot_skyline
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def print_save_plot_skyline(tt, n_std=2.0, screen=True, save='', plot=''):
if plot:
import matplotlib.pyplot as plt
skyline, conf = tt.merger_model.skyline_inferred(gen=50, confidence=n_std)
if save: fh = open(save, 'w', encoding='utf-8')
header1 = "Skyline assuming 50 gen/year and approximate confidence bounds (+/- %f standard deviations of the LH)\n"%n_std
header2 = "date \tN_e \tlower \tupper"
if screen: print('\t'+header1+'\t'+header2)
if save: fh.write("#"+ header1+'#'+header2+'\n')
for (x,y, y1, y2) in zip(skyline.x, skyline.y, conf[0], conf[1]):
if screen: print("\t%1.1f\t%1.1f\t%1.1f\t%1.1f"%(x,y, y1, y2))
if save: fh.write("%1.1f\t%1.1f\t%1.1f\t%1.1f\n"%(x,y, y1, y2))
if save:
print("\n --- written skyline to %s\n"%save)
fh.close()
if plot:
plt.figure()
plt.fill_between(skyline.x, conf[0], conf[1], color=(0.8, 0.8, 0.8))
plt.plot(skyline.x, skyline.y, label='maximum likelihood skyline')
plt.yscale('log')
plt.legend()
plt.ticklabel_format(axis='x',useOffset=False)
plt.savefig(plot)
示例13: plot
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def plot(self, *args, plotTitle=None, showPlot=True, filename=None, **kwargs):
dataFrame = self.select(*args, **kwargs).getDataFrame()
if dataFrame.index.nlevels > 1:
self._raiseException('Please restrict the dataset such that only one index is left.')
ax = dataFrame.plot()
plt.ticklabel_format(useOffset=False, style='plain')
plt.title(plotTitle if plotTitle else kwargs)
self.showPlot(showPlot=showPlot, filename=filename)
return self
示例14: plot_data
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, **kwargs):
if smooth > 1:
"""
smooth data with moving window average.
that is,
smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k])
where the "smooth" param is width of that window (2k+1)
"""
y = np.ones(smooth)
for datum in data:
x = np.asarray(datum[value])
z = np.ones(len(x))
smoothed_x = np.convolve(x,y,'same') / np.convolve(z,y,'same')
datum[value] = smoothed_x
if isinstance(data, list):
data = pd.concat(data, ignore_index=True)
sns.set(style="darkgrid", font_scale=1.5)
sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, ci='sd', **kwargs)
"""
If you upgrade to any version of Seaborn greater than 0.8.1, switch from
tsplot to lineplot replacing L29 with:
sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs)
Changes the colorscheme and the default legend style, though.
"""
plt.legend(loc='best').set_draggable(True)
#plt.legend(loc='upper center', ncol=3, handlelength=1,
# borderaxespad=0., prop={'size': 13})
"""
For the version of the legend used in the Spinning Up benchmarking page,
swap L38 with:
plt.legend(loc='upper center', ncol=6, handlelength=1,
mode="expand", borderaxespad=0., prop={'size': 13})
"""
xscale = np.max(np.asarray(data[xaxis])) > 5e3
if xscale:
# Just some formatting niceness: x-axis scale in scientific notation if max x is large
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
plt.tight_layout(pad=0.5)
示例15: plot_result
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import ticklabel_format [as 别名]
def plot_result(rwd_lst, open_price, close_price):
plt.subplot(211)
# Baseline1: BnH
ret = np.log(close_price / close_price.shift(1))
ret.fillna(0, inplace=True)
bnh = np.cumsum(ret.values) * 2
plt.plot(bnh, label='BnH')
# Baseline2: Momentum
log_ret = np.log(close_price / open_price)
sma = close_price.rolling(30, min_periods=1).mean()
signal = (close_price > sma).shift(1).astype(float) * 4 # shift by 1 since we trade on the next opening price
signal.fillna(0, inplace=True)
mmt = np.cumsum(log_ret.values * signal.values) # convert to cum. simple return
plt.plot(mmt, label='MMT')
# RL agent performance
rl = np.cumsum(rwd_lst)
plt.xticks(())
plt.ylabel('Cumulative Log-Returns')
plt.plot(rl, label='RL')
plt.legend()
def mdd(x):
max_val = None
temp = []
for t in x:
if max_val is None or t > max_val:
max_val = t
temp.append(t - max_val)
return temp
plt.subplot(212)
plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
plt.xlabel('Timesteps')
plt.ylabel('MDD')
plt.plot(mdd(bnh))
plt.plot(mdd(mmt))
plt.plot(mdd(rl))
plt.show()