[英]Plotting grouped data in same plot using Pandas
在熊猫中,我正在做:
bp = p_df.groupby('class').plot(kind='kde')
p_df
是一个dataframe
p_df
对象。
但是,这会产生两个图,每个类一个。 如何在同一情节中强制两个班级的情节?
您可以创建轴,然后使用DataFrameGroupBy.plot
的ax
关键字将所有内容添加到这些轴:
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)
这是结果:
不幸的是,这里的图例标签没有太大意义。
另一种方法是遍历组并手动绘制曲线:
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()
这样您就可以轻松控制图例。 这是结果:
另一种方法是使用seaborn
模块。 这将在同一轴上绘制两个密度估计值,而不指定一个变量来保持轴如下(使用其他答案中的一些数据框设置):
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
# data to create an example data frame
classes = ["c1"] * 5 + ["c2"] * 5
vals = [1,3,5,1,3] + [2,6,7,5,2]
# the data frame
df = pd.DataFrame({"cls": classes, "indices":idx, "vals": vals})
# this is to plot the kde
sns.kdeplot(df.vals[df.cls == "c1"],label='c1');
sns.kdeplot(df.vals[df.cls == "c2"],label='c2');
# beautifying the labels
plt.xlabel('value')
plt.ylabel('density')
plt.show()
这导致以下图像。
import matplotlib.pyplot as plt
p_df.groupby('class').plot(kind='kde', ax=plt.gca())
也许你可以试试这个:
fig, ax = plt.subplots(figsize=(10,8))
classes = list(df.class.unique())
for c in classes:
df2 = data.loc[data['class'] == c]
df2.vals.plot(kind="kde", ax=ax, label=c)
plt.legend()
pandas.DataFrame.groupby
,应指定要绘制的列(例如聚合列)。seaborn.kdeplot
或seaborn.displot
并指定hue
参数pandas v1.2.4
、 matplotlib 3.4.2
、 seaborn 0.11.1
kde
,但对于许多绘图类型(例如kind='line'
、 sns.lineplot
等),步骤是相同的。'kind'
列中,将绘制'duration'
的kde
,忽略'waiting'
。import pandas as pd
import seaborn as sns
df = sns.load_dataset('geyser')
# display(df.head())
duration waiting kind
0 3.600 79 long
1 1.800 54 short
2 3.333 74 long
3 2.283 62 short
4 4.533 85 long
pandas.DataFrame.plot
.groupby
或.pivot
重塑数据.groupby
['duration']
和kind='kde'
。ax = df.groupby('kind')['duration'].plot(kind='kde', legend=True)
.pivot
ax = df.pivot(columns='kind', values='duration').plot(kind='kde')
seaborn.kdeplot
hue='kind'
ax = sns.kdeplot(data=df, x='duration', hue='kind')
seaborn.displot
hue='kind'
和kind='kde'
fig = sns.displot(data=df, kind='kde', x='duration', hue='kind')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.