【发布时间】:2016-05-14 15:53:52
【问题描述】:
我想要做的是子图中的 2x2 图表。然后,对于每个图形,我将使用两个 y 轴。因此,我对每个图表都使用了 twinx() 方法。您在我分享的图中看到的问题是它没有显示第一行的 xlabel 和 xticks。对于第二排,一切都很好。我已经在图中用红色字体指定了问题(“No xlabel and xticks!!!”)。
每个图表都有自己的 x 轴和 y 轴,并且没有共享。
我已经对这段代码进行了很多调整,并缩小了问题制造者的范围。这是因为我在上面的行中使用了 twinx() 。如果我尝试删除辅助 y 轴,一切都会恢复正常,并且上排的 xlabel 和 ylabel 会正确显示。
不知道是什么问题!
这是我正在处理的代码。
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from io import StringIO
s = StringIO(u""" amount price
A 40929 4066443
B 93904 9611272
C 188349 19360005
D 248438 24335536
E 205622 18888604
F 140173 12580900
G 76243 6751731
H 36859 3418329
I 29304 2758928
J 39768 3201269
K 30350 2867059""")
df = pd.read_csv(s, index_col=0, delimiter=' ', skipinitialspace=True)
fig = plt.figure()
ax_2 = fig.add_subplot(222, sharex=None, sharey=None)
ax_22 = ax_2.twinx()
ax_2.plot([1, 3, 5, 7, 9])
ax_22.plot([1.0/x for x in [1, 3, 5, 7, 9]])
ax_2.set_xlabel("AX2 X Lablel")
ax_2.set_ylabel("AX2 Y Lablel")
ax_22.set_ylabel("AX2_Twin Y Lablel")
ax_2 = fig.add_subplot(223, sharex=None, sharey=None)
ax_22 = ax_2.twinx()
ax_2.plot([100, 300, 500, 700, 900])
ax_22.plot([x*x for x in [100, 300, 500, 700, 900]])
ax_2.set_xlabel("AX3 X Lablel")
ax_2.set_ylabel("AX3 Y Lablel")
ax_22.set_ylabel("AX3_Twin Y Lablel")
ax_2 = fig.add_subplot(224, sharex=None, sharey=None)
ax_22 = ax_2.twinx()
ax_2.set_xlabel("AX4 X Lablel")
ax_2.set_ylabel("AX4 Y Lablel")
ax_22.set_ylabel("AX4_Twin Y Lablel")
ax = fig.add_subplot(221, sharex=None, sharey=None)
ax2 = ax.twinx()
width = 0.4
df.amount.plot(kind='bar', color='red', ax=ax, width=width, position=1, sharex=False, sharey=False)
df.price.plot(kind='bar', color='blue', ax=ax2, width=width, position=0, sharex=False, sharey=False)
ax.set_xlabel("Alphabets")
ax.set_ylabel('Amount')
ax2.set_ylabel('Price')
plt.subplots_adjust(wspace=0.8, hspace=0.8)
plt.savefig("t1.png", dpi=300)
plt.show()
生成如下图:
已编辑:
感谢您的回答。但是,在绘图中使用 Pandas 时我的问题仍然存在。我开了一个新问题。请看一下:
matplotlib - pandas - no xlabel and xticks for twinx axes in subploted figures
【问题讨论】:
标签: python pandas matplotlib subplot