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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19952290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:19:58  来源:igfitidea点击:

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

pythonmatplotlibpandas

提问by bigbug

I have a pandas df as below:

我有一个Pandas 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

Then df[['sales','net_pft']].unstack('STK_ID').plot(kind='bar', use_index=True)create bar chart.

然后df[['sales','net_pft']].unstack('STK_ID').plot(kind='bar', use_index=True)创建条形图。

And df[['sales_gr','net_pft_gr']].plot(kind='line', use_index=True)create line chart:

df[['sales_gr','net_pft_gr']].plot(kind='line', use_index=True)创建折线图:

Now I want to put them together in a chart of two y-axes, using twinx().

现在我想使用 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)

The result is like this : enter image description here

结果是这样的: 在此处输入图片说明

My issues are:

我的问题是:

  • How to shift the line to align with the bar at the same x-tickers ?
  • How to let the left and right y_axis tickers aligned at the same line?
  • 如何移动线以与相同 x-tickers 的条对齐?
  • 如何让左右 y_axis 代码在同一条线上对齐?

采纳答案by CT Zhu

Just change the final line to:

只需将最后一行更改为:

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

You will be all set.

你会一切就绪。

enter image description here

在此处输入图片说明

I don't quite get your second question. The 1st and 2nd y axis are of different scale, what do you mean by aligning them to the same line? They can't be aligned to the same grid line (yes you can but the right axis will look ugly, having values like 0.687 and alike). Anyway, you can do:

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

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

to align them, and the plot now looks ugly:

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

enter image description here

在此处输入图片说明