pandas 如何在同一图上显示条形图和折线图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19941685/
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:59  来源:igfitidea点击:

How to show a bar and line graph on the same plot

pythonmatplotlibpandasipython

提问by user2546580

I am unable to show a bar and line graph on the same plot. Example code:

我无法在同一个图上显示条形图和折线图。示例代码:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

Df = pd.DataFrame(data=np.random.randn(10,4), index=pd.DatetimeIndex(start='2005', freq='M', periods=10), columns=['A','B','C','D'])

fig = plt.figure()
ax = fig.add_subplot(111)

Df[['A','B']].plot(kind='bar', ax=ax)
Df[['C','D']].plot(ax=ax, color=['r', 'c'])

回答by Michal

You can also try this:

你也可以试试这个:

fig = plt.figure()
ax = DF['A','B'].plot(kind="bar");plt.xticks(rotation=0)
ax2 = ax.twinx()
ax2.plot(ax.get_xticks(),DF['C','D'],marker='o')

回答by xpt

I wanted to know as well, however all existing answers are not for showing bar and line graph on the sameplot, but on different axis instead.

我也想知道,但是所有现有的答案都不是为了在同一个图上显示条形图和折线图,而是在不同的轴上。

so I looked for the answer myself and have found an example that is working -- Plot Pandas DataFrame as Bar and Line on the same one chart. I can confirm that it works.

所以我自己寻找答案并找到了一个有效的例子 -在同一个图表上将 Pandas DataFrame 绘制为条形图和线形图。我可以确认它有效

What baffled me was that, the almost same code works therebut does not work here. I.e., I copied the OP's code and can verify that it is not working as expected.

让我感到困惑的是,几乎相同的代码在那里工作,在这里不起作用。即,我复制了 OP 的代码并且可以验证它没有按预期工作

The only thing I could think of is to add the index column to Df[['A','B']]and Df[['C','D']], but I don't know how since the index column doesn't have a name for me to add.

我唯一能想到的就是将索引列添加到Df[['A','B']]and Df[['C','D']],但我不知道如何,因为索引列没有名称供我添加。

Today, I realize that even I can make it works, the real problem is that Df[['A','B']]gives a grouped (clustered) bar chart, but grouped (clustered) linechart is not supported.

今天,我意识到即使我可以让它工作,真正的问题是Df[['A','B']]给出了一个分组(集群)条形图,但不支持分组(集群)折线图。

回答by moenad

You can do something like that, both on the same figure:

你可以在同一张图上做类似的事情:

In [4]: Df = pd.DataFrame(data=np.random.randn(10,4), index=pd.DatetimeIndex(start='2005', freq='M', periods=10), columns=['A','B','C','D'])

In [5]: fig, ax = plt.subplots(2, 1) # you can pass sharex=True, sharey=True if you want to share axes.

In [6]: Df[['A','B']].plot(kind='bar', ax=ax[0])
Out[6]: <matplotlib.axes.AxesSubplot at 0x10cf011d0>

In [7]: Df[['C','D']].plot(color=['r', 'c'], ax=ax[1])
Out[7]: <matplotlib.axes.AxesSubplot at 0x10a656ed0>