gpt4 book ai didi

python - 使用辅助 y 轴时,Matplotlib 在前两个子图中不显示 xlabel

转载 作者:太空宇宙 更新时间:2023-11-04 04:25:39 24 4
gpt4 key购买 nike

这个问题与this other one非常相似,但提供的答案并不能解决我的问题,因为它并不完全相同。问题也提到了in this one ,但没有提供任何答案。我希望这个例子能帮助别人指出我的解决方法。

问题是当我使用辅助 y 轴时(使用 pandas 和使用 twinx),xlabels 和 xticklabels 在顶部子图中消失。

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()

最佳答案

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()

enter image description here

关于python - 使用辅助 y 轴时,Matplotlib 在前两个子图中不显示 xlabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53563589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com