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

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

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

pythonpython-3.xpandasmatplotlibbar-chart

提问by Edamame

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. Like in the example figure below:

情节运作良好。但是,我想通过在图中包含 3 列来改进图形:“col_A”、“col_B”和“col_C”。如下图示例所示:

enter image description here

在此处输入图片说明

I would like the col_Adisplayed in blue above x-axis, col_Bin red below x-axis, and col_Cin green above x-axis. Is this something possible in matplotlib? How do I make changes to plot all the three columns? Thanks!

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

回答by ImportanceOfBeingErnest

You can plot several columns at once by supplying a list of column names to the plot's yargument.

您可以通过向ploty参数提供列名列表来一次绘制多个列。

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

enter image description here

在此处输入图片说明

This will produce a graph where bars are sitting next to each other.

这将生成一个图表,其中条形图彼此相邻。

In order to have them overlapping, you would need to call plotseveral times, and supplying the axes to plot to as an argument axto 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()

enter image description here

在此处输入图片说明

回答by ayorgo

Although the accepted answer works fine, since v0.21.0rc1it 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")