matplotlib:在条形图上绘制多列 pandas 数据框 [英] 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()
情节很好.但是,我想通过在图中包含 3 列来改进图形:col_A"、col_B"和col_C".如下图示例所示:
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:
我希望 col_A
在 x 轴上方以蓝色显示,col_B
在 x 轴下方以红色显示,col_C
在上方以绿色显示x 轴.这在 matplotlib 中可能吗?如何更改以绘制所有三列?谢谢!
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!
推荐答案
通过向 plot
的 y
论据.
You can plot several columns at once by supplying a list of column names to the plot
's y
argument.
df.plot(x="X", y=["A", "B", "C"], kind="bar")
这将生成一个图表,其中条形图彼此相邻.
This will produce a graph where bars are sitting next to each other.
为了让它们重叠,您需要多次调用 plot
,并提供要绘制的坐标轴作为绘图的参数 ax
.>
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.
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()
这篇关于matplotlib:在条形图上绘制多列 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!