如何在matplotlib两个y轴图表中对齐条形图和直线?

2024-06-02 06:30:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一只熊猫df如下:

>>> 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)创建折线图:

现在我想用twinx()把它们放在一个由两个y轴组成的图表中。

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-tickers上移动行以与条对齐?
  • 如何让左y轴和右y轴在同一条线上对齐?

Tags: idtruedfindexnetplotusebar
1条回答
网友
1楼 · 发布于 2024-06-02 06:30:02

把最后一行改成:

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

为了使它们对齐,现在的情节看起来很难看:

enter image description here

相关问题 更多 >