【问题标题】:How to set scientific notation on axis in matplotlib如何在 matplotlib 中设置轴上的科学记数法
【发布时间】:2018-10-13 12:48:51
【问题描述】:

我正在尝试用两个单独的 x 轴绘制图表。一个是一些阀门打开,另一个是相应的泄漏率。我设法使它工作得很好,尽管该辅助轴的格式并不总是显示科学记数法,如下图所示 Awful overlapping labels, see the upper axis 如何强制科学计数法显示,使标签不会重叠? 这是我正在使用的脚本:

#HEADERS
import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.ticker

from matplotlib import rc
rc('font', **{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
#/HEADERS

turns = np.array([11.000, 11.500, 11.750, 12.000, 12.250, 12.375])
leak = np.array([3.89e-05, 4.63e-05, 1.67e-04, 1.45000000e-03, 8.61e-03, 1.71e-02])
pressure1 = np.array([7.9e-07, 3.0e-06, 3.5e-05, 6.1e-04, 5.1e-03, 1.8e-02])
pressure2 = np.array([8.22e-07, 8.22e-07, 8.71e-07, 1.8e-06, 1.150e-05, 7.24e-05])
pressure3 = np.array([2e-06, 2e-06, 2e-06, 1.2e-05, 1.2e-04, 6e-04])

fig = plt.figure(num='valve', figsize = (6.68, 6.68*1.3))
fig, ax1 = plt.subplots()
ax1.plot(turns, pressure1, 'r.', label= '$P_1$')
ax1.plot(turns, pressure2, 'b.', label= '$P_2$')
ax1.plot(turns, pressure3,'k.', label= '$P_3$')

plt.legend()

plt.minorticks_on()
plt.grid(b = True, which = 'major', axis = 'both')

ax1.errorbar(turns, pressure1, yerr = .4*pressure1, fmt='none', ecolor = 'k', elinewidth = 1, capsize = 1, label= '$P_{1err}$')
ax1.errorbar(turns, pressure2, yerr = .15*pressure2, fmt='none', ecolor = 'k', elinewidth = 1, capsize = 1, label= '$P_{2err}$')

plt.rc('text', usetex=True)
plt.rc('font', family='serif')

ax1.set_yscale('log', nonposy = 'mask')
ax1.set_ylabel(r'$P$')
ax1.set_xscale('linear')
ax1.set_xlabel('Opening (turns)')
plt.minorticks_on()
#plt.grid(b = True, which = 'major', axis = 'both')

#adding a secondary x-axis above
ax2 = ax1.twiny()
ax2.set_xlim(ax1.get_xlim())
new_tick_locations = turns
new_tick_label = leak #dtype here ?
ax2.set_xticks(new_tick_locations)
ax2.set_xticklabels(new_tick_label)
# I tried those commands from other threads but they all result in an error.
#ax2.xaxis.set_scientific(True)
#ax2.get_xaxis().set_major_formatter((matplotlib.ticker.Formatter(set_scientific(True)))
#ax2.get_xaxis().set_major_formatter().set_scientific(True)

ax2.set_xlabel(r'Leak rate (mbar$\times$L/s)')

plt.tight_layout()

#export png
plt.savefig(('export.png'), format = 'png', transparent=False, dpi = 300)
plt.show()

我使用的是 Python 3.6。

感谢您的帮助。

【问题讨论】:

标签: python-3.x matplotlib axis-labels


【解决方案1】:

由于您覆盖了刻度,您可以自己格式化它们并旋转它们以获得更多空间:

new_tick_label = ['{:5.2e}'.format(x) for x in leak] 
ax2.set_xticks(new_tick_locations)
ax2.set_xticklabels(new_tick_label, rotation=30)

结果:

【讨论】:

  • 谢谢,我刚试过,但它现在将波纹管标签显示为科学数字。好像 ax2 标签被忽略了一样。
  • 用不同的方法解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 2022-01-22
  • 2014-11-03
  • 1970-01-01
  • 2018-03-25
  • 2016-08-15
  • 1970-01-01
  • 2015-10-09
相关资源
最近更新 更多