首页 > 解决方案 > 你如何在 Seaborn 中为 kde 情节创造传奇?

问题描述

我有一个 kdeplot,但我正在努力弄清楚如何创建图例。

import matplotlib.patches as mpatches  # see the tutorial for how we use mpatches to generate this figure!

# Set 'is_workingday' to a boolean array that is true for all working_days
is_workingday = daily_counts["workingday"] == "yes"
is_not_workingday = daily_counts['workingday'] == "no"
# Bivariate KDEs require two data inputs. 
# In this case, we will need the daily counts for casual and registered riders on workdays
casual_workday = daily_counts.loc[is_workingday, 'casual']
registered_workday = daily_counts.loc[is_workingday, 'registered']

# Use sns.kdeplot on the two variables above to plot the bivariate KDE for weekday rides
sns.kdeplot(casual_workday, registered_workday, color = "red", cmap = "Reds", hue = "workingday", legend = True)

# Repeat the same steps above but for rows corresponding to non-workingdays
casual_non_workday =  daily_counts.loc[is_not_workingday, 'casual']
registered_non_workday = daily_counts.loc[is_not_workingday, 'registered']


# Use sns.kdeplot on the two variables above to plot the bivariate KDE for non-workingday rides
sns.kdeplot(casual_non_workday, registered_non_workday, color = 'blue', cmap = "Blues", legend = True, shade = False)

得到我这个: 在此处输入图像描述

我试图得到这个: 在此处输入图像描述

标签: pythonplotseabornlegend

解决方案


一种方法是传递一个label=tokdeplot然后请求显示图例。

geyser = sns.load_dataset("geyser")
long = geyser.loc[geyser['kind']=='long']
short = geyser.loc[geyser['kind']=='short']
sns.kdeplot(x=long["waiting"], y=long["duration"], label='long')
sns.kdeplot(x=short["waiting"], y=short["duration"], label='short')
plt.legend()

在此处输入图像描述

另一种方法是使用 seaborn 必须基于列拆分数据框的内置方式hue=。在你的情况下,它看起来像下面,但不知道你的数据框的结构,不可能确定。有关更多信息,请参阅文档

sns.kdeplot(x='casual', y='registered', hue='workingday', data=daily_counts, shade=False, legend=True)

推荐阅读