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

2024-04-26 12:58:43 发布

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

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

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'])

Tags: 代码import绘图示例pandasdfplotas
3条回答

你可以这样做,两个都在同一个图形上:

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>

您也可以尝试:

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

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

所以我自己寻找答案,找到了一个有效的例子——Plot Pandas DataFrame as Bar and Line on the same one chart。我可以确认它是works

令我困惑的是,几乎相同的代码works there但是does not work here。一、 我复制了操作系统的代码,可以verify that it is not working as expected

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

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

相关问题 更多 >