使用 pandas 在同一图中绘制分组数据 [英] Plotting grouped data in same plot using Pandas
本文介绍了使用 pandas 在同一图中绘制分组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在做熊猫:
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?
推荐答案
版本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屋!
查看全文