Skip to main content
 首页 » 编程设计

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

2024年12月31日8mfrbuaa

这个问题与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()