Matplotlib не показывает xlabel в двух верхних графиках при использовании вторичной оси y - PullRequest
0 голосов
/ 30 ноября 2018

Этот вопрос очень похож на этот другой , но предоставленный ответ не решает мою проблему, поскольку он не совсем такой же.Также проблема была передана в этом , но ответа не было.Я надеюсь, что этот пример поможет кому-то указать мне обходной путь.

Проблема в том, что когда я использую вторичную ось y (как с пандами, так и с помощью 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()

1 Ответ

0 голосов
/ 30 ноября 2018

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...