如何在添加另一个y轴时旋转x轴标签?

4 投票
1 回答
2093 浏览
提问于 2025-04-17 07:25

不知道为什么,当我在我的图表上添加第二个y轴后,

fig.plt.figure()
ax = plt.Axes(fig)
fig.add_axes(ax)
ax2 = ax.twinx()
fig.add_axes(ax2)

x轴的标签就不再旋转了!?

fig.autofmt_xdate(rotation = num)

有没有人知道这是为什么呢?

我可以把最后两行代码注释掉:

#ax2 = ax.twinx()
#fig.add_axes(ax2)

这样x轴的标签就会旋转了。

1 个回答

7

fig.autofmt_xdate(rotation = num) 这行代码放在定义 ax 的语句之后,但要在调用 ax.twinx() 之前。这样做会得到:

import matplotlib.pyplot as plt
import matplotlib.dates as md
import datetime as dt
import numpy as np

np.random.seed(0)
t=md.drange(dt.datetime(2009,10,1),
            dt.datetime(2010,1,15),
            dt.timedelta(days=1))
n=len(t)
x1 = np.cumsum(np.random.random(n) - 0.5) * 40000
x2 = np.cumsum(np.random.random(n) - 0.5) * 0.002

fig = plt.figure()
# fig.autofmt_xdate(rotation=25) # does not work
ax1 = fig.add_subplot(1,1,1)
fig.autofmt_xdate(rotation=25) # works
ax2 = ax1.twinx()
# fig.autofmt_xdate(rotation=25) # does not work
ax1.plot_date(t, x1, 'r-')
ax2.plot_date(t, x2, 'g-')
plt.show()

结果是

enter image description here

撰写回答