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

标签 python matplotlib pandas

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

然后 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_axis tickers 对齐在同一条线上?

最佳答案

只需将最后一行更改为:

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

关于python - 如何对齐 matplotlib 两个 y 轴图表中的条形图和线条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19952290/

相关文章:

python - 强制用户使用 PySimpleGui 选择文件?

python - 如何使用 groupby 将多个函数应用于 Pandas 中的多个列?

python - 如果一个是 imshow 图,请在 matplotlib 中垂直对齐两个图?

python - 为什么在python中通过字符串声明unicode?

python - 为什么 super().__init__ 在子类化 threading.Thread 时不起作用?

python - 对 Pandas Dataframe 中不同列的多索引

python - 将 Pandas Dataframe 中的特定列添加到另一个 Pandas Dataframe

python - 将元组索引转换为日期时间索引

python - 在 python 中导入 Pandas 会改变 matplotlib 处理日期时间对象的方式吗?

python - 使用 matplotlib 更改 python 条形图中日期时间数据的 x 轴刻度标签的频率