我有以下代碼:
import matplotlib.pyplot as plt
from matplotlib.ticker import (MultipleLocator,
FormatStrFormatter,
AutoMinorLocator)
params = {
'text.usetex' : True,
'font.size' : 18,
'font.family' : 'lmodern',
}
plt.rcParams.update(params) # <--- without font settings FormatStrFormatter works
x = [1, 5, 6]
y = [-800, 600, -300]
fig, (ax1, ax2) = plt.subplots(figsize = (10,10), nrows=2, ncols=1)
ax1.plot(x, y)
ax2.plot(x, y)
ax1.yaxis.set_ticks_position('both')
ax2.yaxis.set_ticks_position('both')
ax1.tick_params(axis="y", labelright=True)
ax2.tick_params(axis="y", labelright=True)
ax1.yaxis.set_major_formatter(FormatStrFormatter('%4.0f'))
ax2.yaxis.set_major_formatter(FormatStrFormatter('%4.0f'))
plt.show()
給出這個結果:

如何更好地對齊右側 y 軸上的數字?
當我評論
#plt.rcParams.update(params)
我得到了想要的結果:

請問如何在代碼中設定這種對齊方式和字體?甚至更好 - 如何在 2、4、6、8(左側)或單位(右側)下對齊零?
咨詢后:
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
params = {
'text.usetex' : True,
'font.size' : 10,
'font.family' : 'lmodern',
}
plt.rcParams.update(params) # <--- without font settings FormatStrFormatter works
x = [1, 5, 6]
y = [-800, 600, -300]
fig, (ax1, ax2) = plt.subplots(figsize = (10,10), nrows=2, ncols=1)
ax1.plot(x, y)
ax2.plot(x, y)
ax1.yaxis.set_ticks_position('both')
ax2.yaxis.set_ticks_position('both')
ax1.tick_params(axis="y", labelright=True)
ax2.tick_params(axis="y", labelright=True)
ax1.yaxis.set_major_locator(MultipleLocator(200))
ax1.yaxis.set_major_locator(MultipleLocator(200))
plt.tight_layout()
plt.show()

uj5u.com熱心網友回復:
如果分離繪圖的左右軸,則可以單獨更改它們的對齊和填充。
完整代碼:
import numpy as np
import matplotlib.pyplot as plt
params = {
'text.usetex' : True,
'font.size' : 10,
'font.family' : 'lmodern',
}
plt.rcParams.update(params) # <--- without font settings FormatStrFormatter works
x = [1, 5, 6]
y = [-800, 600, -300]
ax_dist = 100
fig, (ax1, ax3) = plt.subplots(figsize = (10,10), nrows=2, ncols=1)
ax1.plot(x, y)
ax3.plot(x, y)
ax2 = ax1.twinx()
ax4 = ax3.twinx()
ax1.set_ylim([- ax_dist min(y), ax_dist max(y)])
ax2.set_ylim(ax1.get_ylim())
ax3.set_ylim(ax1.get_ylim())
ax4.set_ylim(ax1.get_ylim())
for tick2, tick4 in zip(ax2.yaxis.get_majorticklabels(), ax4.yaxis.get_majorticklabels()):
tick2.set_horizontalalignment("right")
tick4.set_horizontalalignment("right")
for tick2, tick4 in zip(ax2.get_yaxis().get_major_ticks(), ax4.get_yaxis().get_major_ticks()):
tick2.set_pad(24)
tick4.set_pad(24)
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/452285.html
