0

I have a boxplot in Seaborn/Matplotlib for multiple categorical data:

plot

The problem is the legend part does not match with the plot color.

data = pd.DataFrame.from_dict(data)
print(data.head())
model_names = ['T5B', 'NatGen']
dfl = pd.melt(data, id_vars='metric', value_vars= ['T5B', 'NatGen'])
sns.boxplot(x= 'metric' , y='value', data=dfl, showfliers=False, color='tomato', hue='variable')
plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0, labels = model_names)
plt.show()

P.S:

print(df.head())

Would yield:

   metric variable     value
0  syntax      T5B  0.071429
1  syntax      T5B  0.086957
2  syntax      T5B  0.090909
3  syntax      T5B  0.071429
4  syntax      T5B  0.125000
m0ss
  • 334
  • 2
  • 4
  • 17
  • 3
    Use sns.move_legend, not plt.legend: https://stackoverflow.com/a/68849891/7758804 Without data, this is not a complete [mre]. – Trenton McKinney Feb 21 '23 at 23:47
  • 2
    If you want the labels to be different in the legend, then map the column values to appropriate string. Data cleaning should occur prior to plotting. `labels = model_names` is causing the issue. `df.variable = df.variable.map({'value in column': 'new value', ...})` – Trenton McKinney Feb 22 '23 at 01:56
  • 2
    Otherwise you must also provide the `handles` to `ax.legend` as shown in this [question](https://stackoverflow.com/q/62069967/7758804): `handles, _ = ax.get_legend_handles_labels()` and `ax.legend(handles=handles, labels=model_names)`. [code and plot](https://i.stack.imgur.com/rarFu.png) – Trenton McKinney Feb 22 '23 at 02:03

0 Answers0