繁体   English   中英

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

[英]How to align the bar and line in matplotlib two y-axes chart?

我有一个熊猫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)

结果是这样的: 在此输入图像描述

我的问题是:

  • 如何在相同的x-tickers上移动线条与杆对齐?
  • 如何让左右y_axis代码在同一行对齐?

只需将最后一行更改为:

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

你将全力以赴。

在此输入图像描述

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

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

对齐它们,情节现在看起来很难看:

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM