matplotlib:在条形图ch上绘制pandas数据框的多列

2024-04-20 00:04:04 发布

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

我使用以下代码绘制条形图:

import matplotlib.pyplot as pls 
my_df.plot(x='my_timestampe', y='col_A', kind='bar') 
plt.show()

情节很好。不过,我想改进这个图,在图上加上3列:“colúA”、“colúB”和“colúC”。如下图所示:

enter image description here

我希望x轴上方的col_A显示为蓝色,x轴下方的col_B显示为红色,x轴上方的col_C显示为绿色。这在matplotlib中有可能吗?如何更改打印所有三列?谢谢!


Tags: 代码importdfplotmatplotlibmyas绘制
2条回答

尽管接受的答案很好,但由于v0.21.0rc1它给出了一个警告

UserWarning: Pandas doesn't allow columns to be created via a new attribute name

相反,我们可以

df[["X", "A", "B", "C"]].plot(x="X", kind="bar")

通过向ploty参数提供列名列表,可以同时绘制多个列。

df.plot(x="X", y=["A", "B", "C"], kind="bar")

enter image description here

这将产生一个图表,其中的酒吧坐在彼此旁边。

为了使它们重叠,您需要多次调用plot,并提供要绘制的轴作为绘图的参数ax

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

y = np.random.rand(10,4)
y[:,0]= np.arange(10)
df = pd.DataFrame(y, columns=["X", "A", "B", "C"])

ax = df.plot(x="X", y="A", kind="bar")
df.plot(x="X", y="B", kind="bar", ax=ax, color="C2")
df.plot(x="X", y="C", kind="bar", ax=ax, color="C3")

plt.show()

enter image description here

相关问题 更多 >