如何将柱状图和折线图与第二个y轴对齐

18
我有一个如下的pandas数据框:
>>> df
                   sales  net_pft  sales_gr  net_pft_gr
STK_ID RPT_Date                                        
600809 20120331  22.1401   4.9253    0.1824     -0.0268
       20120630  38.1565   7.8684    0.3181      0.1947
       20120930  52.5098  12.4338    0.4735      0.7573
       20121231  64.7876  13.2731    0.4435      0.7005
       20130331  27.9517   7.5182    0.2625      0.5264
       20130630  40.6460   9.8572    0.0652      0.2528
       20130930  53.0501  11.8605    0.0103     -0.0461

然后df[['sales','net_pft']].unstack('STK_ID').plot(kind='bar', use_index=True)创建柱状图。
df[['sales_gr','net_pft_gr']].plot(kind='line', use_index=True)创建折线图:
现在我想将它们放在一个具有两个y轴的图表中,使用twinx()。
import matplotlib.pyplot as plt
fig = plt.figure()
ax = df[['sales','net_pft']].unstack('STK_ID').plot(kind='bar', use_index=True)
ax2 = ax.twinx()
ax2.plot(df[['sales_gr','net_pft_gr']].values, linestyle='-', marker='o', linewidth=2.0)

结果如下: enter image description here

我的问题是:
  • 如何将线条移动以与相同x轴刻度对齐?
  • 如何让左右y轴刻度对齐在同一条线上?
1个回答

16

只需将最后一行更改为:

ax2.plot(ax.get_xticks(),
         df[['sales_gr','net_pft_gr']].values,
         linestyle='-',
         marker='o', linewidth=2.0)

你就准备好了。

enter image description here

我不太明白你的第二个问题。第一和第二个 y 轴具有不同的比例,你说的将它们对齐到同一条线是什么意思?它们不能对齐到同一条网格线上(当然你可以这样做,但右边的轴会看起来很丑,有像 0.687 等的值)。无论如何,你可以这样做:

ax.set_ylim((-10, 80.))

为了对齐它们,现在的图表看起来很丑陋:

在此输入图像描述


不用谢,你很受欢迎。现在在中国,Pandas、NumPy和SciPy也很流行吗? - CT Zhu
2
如果你使用Python进行一些不错的计算,迟早会需要NumPy,然后是Pandas,无论你在哪里... - bigbug

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接