python - matplotlib:在条形图上绘制多列 Pandas 数据框

标签 python python-3.x pandas matplotlib bar-chart

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

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

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

最佳答案

您可以通过向 plot 提供列名列表来一次绘制多个列。的y争论。

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

关于python - matplotlib:在条形图上绘制多列 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42128467/

相关文章:

Python 合并 2 个列表/SQL JOIN

python - 数据框到字典列表

python - 在 Python 中,是否有直接的方法来过滤 pd.dataframe 以列的 2 个值范围为条件?

python - 类型错误 Iter - Python3

python - 循环遍历文本,一次 3 个字符

移动数组元素的Python程序

python - Pandas - rank() 函数的替代方案,它为列提供唯一的序数等级

python - 从 URL 更新 Pandas Dataframe,但不包含列,并且每分钟更新一次,而不是每 60 秒更新一次

python - 在 Pandas Dataframe 中查找重复行,然后在 Dataframe 中添加一列,说明该行是否重复

python - 在模板中显示时缩小图像尺寸