use*_*999 37 python plot pandas
在熊猫,我正在做:
bp = p_df.groupby('class').plot(kind='kde')
Run Code Online (Sandbox Code Playgroud)
p_df
是一个dataframe
对象.
然而,这产生了两个图,每个类一个.如何在同一个图中强制同时使用两个类的一个图?
cel*_*cel 61
您可以创建轴,然后使用ax
关键字DataFrameGroupBy.plot
to将所有内容添加到这些轴:
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)
Run Code Online (Sandbox Code Playgroud)
这是结果:
不幸的是,传说的标签在这里没有太大意义.
另一种方法是循环遍历组并手动绘制曲线:
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()
Run Code Online (Sandbox Code Playgroud)
这样您就可以轻松控制图例.这是结果:
dag*_*ili 11
另一种方法是使用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()
Run Code Online (Sandbox Code Playgroud)
这导致以下图像.
sp0*_*n3r 10
import matplotlib.pyplot as plt
p_df.groupby('class').plot(kind='kde', ax=plt.gca())
Run Code Online (Sandbox Code Playgroud)
pandas.DataFrame.groupby
,应指定要绘制的列(例如聚合列)。seaborn.kdeplot
orseaborn.displot
并指定hue
参数pandas v1.2.4
,matplotlib 3.4.2
,seaborn 0.11.1
kde
步骤是相同的。kind='line'
sns.lineplot
'kind'
列中,并且将绘制 的 ,kde
忽略。'duration'
'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
Run Code Online (Sandbox Code Playgroud)
pandas.DataFrame.plot
.groupby
使用或重塑数据.pivot
.groupby
['duration']
和kind='kde'
。ax = df.groupby('kind')['duration'].plot(kind='kde', legend=True)
Run Code Online (Sandbox Code Playgroud)
.pivot
ax = df.pivot(columns='kind', values='duration').plot(kind='kde')
Run Code Online (Sandbox Code Playgroud)
seaborn.kdeplot
hue='kind'
ax = sns.kdeplot(data=df, x='duration', hue='kind')
Run Code Online (Sandbox Code Playgroud)
seaborn.displot
hue='kind'
和kind='kde'
fig = sns.displot(data=df, kind='kde', x='duration', hue='kind')
Run Code Online (Sandbox Code Playgroud)
小智 5
也许你可以尝试这个:
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()
Run Code Online (Sandbox Code Playgroud)