- How can each
hue group of a seaborn.kdeplot, or seaborn.displot with kind='kde' be given a different linestyle?
- Both axes-level and figure-level options will accept a
str for linestyle/ls, which applies to all hue groups.
import seaborn as sns
import matplotlib.pyplot as plt
# load sample data
iris = sns.load_dataset("iris")
# convert data to long form
im = iris.melt(id_vars='species')
# axes-level plot works with 1 linestyle
fig = plt.figure(figsize=(6, 5))
p1 = sns.kdeplot(data=im, x='value', hue='variable', fill=True, ls='-.')
# figure-level plot works with 1 linestyle
p2 = sns.displot(kind='kde', data=im, x='value', hue='variable', fill=True, ls='-.')


Reviewed Questions
fill=Truethe object to update is in.collectionsfill=Falsethe object to update is in.lineshandles = p.legend_.legendHandles[::-1]extracts and reverses the legend handles. They're reversed to update because they're in the opposite order in which the plotlinestyleis updated._legend, with the axes-level plots use.legend_.python 3.8.12,matplotlib 3.4.3,seaborn 0.11.2kdeplot: axes-level.collectionsor.linesfrom theaxesobject and use.set_linestylefill=Truefill=Falsedisplot: figure-levelhandlescould be updated infor line, ls, handle in zip(ax.collections, lss, handles), but that applies the update for each subplot. Therefore, a separate loop is created to update the legendhandlesonly once.fill=Truefill=False