使用 Pandas 在同一图中绘制分组数据 [英] Plotting grouped data in same plot using Pandas
本文介绍了使用 Pandas 在同一图中绘制分组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Pandas 中,我正在做:
In Pandas, I am doing:
bp = p_df.groupby('class').plot(kind='kde')
p_df
是一个 dataframe
对象.
然而,这会产生两个图,每个类一个.如何在同一情节中强制两个班级的情节?
However, this is producing two plots, one for each class. How do I force one plot with both classes in the same plot?
推荐答案
Version 1:
您可以创建轴,然后使用 DataFrameGroupBy.plot
将所有内容添加到这些轴:
Version 1:
You can create your axis, and then use the ax
keyword of DataFrameGroupBy.plot
to add everything to these axes:
import matplotlib.pyplot as plt
p_df = pd.DataFrame({"class": [1,1,2,2,1], "a": [2,3,2,3,2]})
fig, ax = plt.subplots(figsize=(8,6))
bp = p_df.groupby('class').plot(kind='kde', ax=ax)
结果如下:
不幸的是,图例的标签在这里没有太大意义.
Unfortunately, the labeling of the legend does not make too much sense here.
另一种方法是遍历组并手动绘制曲线:
Another way would be to loop through the groups and plot the curves manually:
classes = ["class 1"] * 5 + ["class 2"] * 5
vals = [1,3,5,1,3] + [2,6,7,5,2]
p_df = pd.DataFrame({"class": classes, "vals": vals})
fig, ax = plt.subplots(figsize=(8,6))
for label, df in p_df.groupby('class'):
df.vals.plot(kind="kde", ax=ax, label=label)
plt.legend()
这样您就可以轻松控制图例.结果如下:
This way you can easily control the legend. This is the result:
这篇关于使用 Pandas 在同一图中绘制分组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文