Как установить научное обозначение на оси в matplotlib - PullRequest
0 голосов
/ 03 мая 2018

Я пытаюсь построить график с двумя отдельными осями X. Один из них является некоторым открытием клапана, а другой - соответствующей скоростью утечки. Мне удалось заставить его работать довольно хорошо, хотя формат этой вторичной оси не всегда показывает научные обозначения, как показано на рисунке ниже Ужасные перекрывающиеся метки, см. Верхнюю ось Как заставить отображение научной нотации так, чтобы этикетки не перекрывались? Вот скрипт, который я использую:

#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.

Спасибо за вашу помощь.

1 Ответ

0 голосов
/ 03 мая 2018

Поскольку вы переопределяете галочки, вы можете отформатировать их и повернуть, чтобы получить больше места:

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)

Результат:

enter image description here

...