【问题标题】:Share x-axis when using secondary y-axis使用辅助 y 轴时共享 x 轴
【发布时间】:2020-03-28 06:21:21
【问题描述】:

在使用基于 pandas 数据框的辅助 y 轴创建图表时,我很难共享 x 轴。我主要从解决方案here 借钱,我喜欢接受答案的编辑。

在使用我自己的玩具数据框重新创建此解决方案时,我面临的问题是我的 x 轴看起来不太好。

df = pd.DataFrame(np.random.randint(0, 100, (20, 2)),
                  index=pd.date_range('20190101', periods=20),
                  columns=list('AB'))

fig, ax = plt.subplots()

ax.plot(df.index, df['A'], 'blue', label='Line A')

ax2 = ax.twinx()
ax2.plot(df.index, df['B'], 'red', label='Line B')

lines = ax.get_lines() + ax2.get_lines()

ax.legend(lines, [l.get_label() for l in lines],
          loc='upper left', frameon=False, fontsize=20)

【问题讨论】:

    标签: python pandas matplotlib graph charts


    【解决方案1】:

    您可以使用 pandas 的内置命令,它提供了一些有趣的刻度标签:

    fig, ax = plt.subplots()
    df.plot(y=['A','B'], secondary_y='B', ax=ax)
    

    输出:

    【讨论】:

      【解决方案2】:

      解决此问题的一种方法是旋转 x-tick 标签:

      df = pd.DataFrame(np.random.randint(0, 100, (20, 2)),
                        index=pd.date_range('20190101', periods=20),
                        columns=list('AB'))
      
      fig, ax = plt.subplots()
      plt.xticks(rotation=70)
      
      ax.plot(df.index, df['A'], 'blue', label='Line A')
      
      ax2 = ax.twinx()
      ax2.plot(df.index, df['B'], 'red', label='Line B')
      
      lines = ax.get_lines() + ax2.get_lines()
      
      
      
      ax.legend(lines, [l.get_label() for l in lines],
                loc='upper left', frameon=False, fontsize=20)
      

      输出:

      另一种选择是增加图形大小或减小标签字体大小,以便标签不再重叠。

      fig, ax = plt.subplots(figsize=(15,10))
      

      输出:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-06
        • 1970-01-01
        • 2021-03-22
        • 1970-01-01
        相关资源
        最近更新 更多