这个问题与this other one非常相似,但是提供的答案并不完全相同,因此无法解决我的问题。该问题也已提到in this one,但未提供答案。我希望这个例子可以帮助有人指出我的解决方法。
问题是当我使用辅助y轴(同时与pandas和twinx一起使用)时,xlabel和xticklabel消失在顶部子图上。
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame([[1,2,4,6],[1,2,6,10],[2,4,12,12],[2,4,12,14],
[3,8,14,16],[3,8,14,18],[4,10,16,20],[4,10,16,24]],
columns =['A','B','C','D'])
fig, axes = plt.subplots(2,2)
for xx, ax in zip(['A','B','C'], axes.flatten()):
meandf = df.groupby(xx).mean()
df.plot(xx, 'D', ax = ax, legend=False)
#adding the secondary_y makes x labels and ticklabels disappear on top subplots
#without secondary_y it will show the labels and ticklabels
meandf.plot(meandf.index, 'D', secondary_y='D', ax = ax)
#forcing does not help
ax.set_xlabel(xx)
# typically it is a matter of using tight_layout, but does not solve
# setting a bigger space between the rows does not solve it either
plt.tight_layout()
答案 0 :(得分:1)
KeyErrors
之外,坚持使用原始的matplotlib可能是您最好的选择:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(
[[1, 2, 4, 6], [1, 2, 6, 10], [2, 4, 12, 12], [2, 4, 12, 14],
[3, 8, 14, 16], [3, 8, 14, 18], [4, 10 ,16, 20], [4, 10 ,16, 24]],
columns =['A', 'B', 'C', 'D']
)
fig, axes = plt.subplots(2, 2)
for xx, ax1 in zip(['A','B','C'], axes.flatten()):
meandf = df.groupby(xx).mean()
# explicitly create and save the secondary axis
ax2 = ax1.twinx()
# plot on the main ax
ax1.plot(xx, 'D', 'ko', data=df)
# plot on the secondary ax
ax2.plot('D', 'gs', data=meandf)
# set the label
ax1.set_xlabel(xx)
fig.tight_layout()