Change colour and leged order for a KDE matplotlib.plot

Viewed 56
df.groupby("class").q1.plot(kind='kde')
plt.title('Age')
plt.xlabel('Score obtained in age')
plt.ylabel('Density')
plt.legend()
plt.savefig(f'Analysis/q1-kde.png')
plt.close()
label_order=["Very Low", "Low", 'Average', 'High', 'Very High']

and get something like:

enter image description here

However, the legend labels are sorted alphabetically. I would like to have the order of the legend and of kde line as the one defined in label_order

1 Answers

Use categorical dtype with ordered:

label_order=["Very Low", "Low", 'Average', 'High', 'Very High']
df['class'] = pd.Categorical(df['class'], categories=label_order, ordered=True)

df.groupby("class").q1.plot(kind='kde')

plt.title('Age')
plt.xlabel('Score obtained in age')
plt.ylabel('Density')
plt.legend()

Output:

enter image description here

Related