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
matplotlib: plot multiple columns of pandas data frame on the bar 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”。如下图示例所示:
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. Is this something possible in matplotlib? How do I make changes to plot all the three columns? Thanks!
我希望col_A
x 轴上方以蓝色显示,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 y
argument.
您可以通过向plot
的y
参数提供列名列表来一次绘制多个列。
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()
回答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")