How To Change Legend Position In Seaborn Kdeplot?
I try to change kdeplot legend position. unfortunelly position is changed but contents is not showing. outline only. My code is: import pandas as pd import seaborn as sns import m
Solution 1:
For some strange reason, the current seaborn (0.11.0
) and matplotlib (3.3.2
) versions give an error No handles with labels found to put in legend.
But the following approach seems to work. Note that _set_loc(2)
only accepts a code, not a string, where 2
corresponds to 'upper left'
.
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame({"c": np.random.randn(10000).cumsum(),
"scan": np.repeat([*'abcd'], 2500)})
ax = sns.kdeplot(data=df, x="c", hue="scan", shade=True, palette="deep")
ax.legend_.set_bbox_to_anchor((0.05, 0.95))
ax.legend_._set_loc(2)
plt.show()
PS: Explicitly providing the legend labels also seems to work, but then probably hue_order
is needed to ensure the order is the same.
scan_labels = np.unique(df['scan'])
ax = sns.kdeplot(data=df, x="c", hue="scan", hue_order=scan_labels, shade=True, palette="deep", legend=True)
ax.legend(labels=scan_labels, bbox_to_anchor=(0.05, 0.95), loc='upper left', title='scan')
Post a Comment for "How To Change Legend Position In Seaborn Kdeplot?"