简体   繁体   English

matplotlib:在条形图上绘制多列熊猫数据框

[英]matplotlib: plot multiple columns of pandas data frame on the bar chart

I am using the following code to plot a bar-chart:我正在使用以下代码绘制条形图:

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

The plot works fine.情节运作良好。 However, I want to improve the graph by having 3 columns: 'col_A', 'col_B', and 'col_C' all on the plot.但是,我想通过在图中包含 3 列来改进图形:“col_A”、“col_B”和“col_C”。 Like in the example figure below:如下图示例所示:

在此处输入图片说明

I would like the col_A displayed in blue above x-axis, col_B in red below x-axis, and col_C in green above x-axis.我希望col_A在 x 轴上方以蓝色显示, col_B在 x 轴col_B以红色显示, col_B在 x 轴上col_C以绿色显示。 Is this something possible in matplotlib?这在 matplotlib 中可能吗? How do I make changes to plot all the three columns?如何更改以绘制所有三列? Thanks!谢谢!

You can plot several columns at once by supplying a list of column names to the plot 's y argument.您可以通过向ploty参数提供列名列表来一次绘制多个列。

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

在此处输入图片说明

This will produce a graph where bars are sitting next to each other.这将生成一个图表,其中条形图彼此相邻。

In order to have them overlapping, you would need to call plot several times, and supplying the axes to plot to as an argument ax to the plot.为了让它们重叠,您需要多次调用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()

在此处输入图片说明

Although the accepted answer works fine, since v0.21.0rc1 it gives a warning虽然接受的答案工作正常,但自v0.21.0rc1以来它发出警告

UserWarning: Pandas doesn't allow columns to be created via a new attribute name用户警告:Pandas 不允许通过新的属性名称创建列

Instead, one can do相反,你可以做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM