3
votes

I am new to Python.

I have generated a boxplot (with a swarmplot overlay) in matplotlib/seaborn using the following code. I would now like to add a legend that follows the color scheme of each box. Many solutions I find online does not seem to apply to this particular type of graph (eg. only work with grouped boxplots).

When I try to implement the code suggested here I receive the error message.

enter image description here

All input is greatly appreciated!

# Import libraries and modules

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Set seaborn style.

sns.set(style="whitegrid", palette="colorblind")

# Load summary tidy data.

tidy = pd.read_csv('tidy.csv')

# Define plots for tidy data

fig, ax = plt.subplots(figsize=(10,6))
ax = sns.boxplot(x='header1', y='header2', data=tidy, order=["header1", "header2"])
ax = sns.swarmplot(x="header1", y="header2", data=tidy, color=".25", order=["header1", "header2"])
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[0] = 'header1'
labels[1] = 'header2'
ax.set_xticklabels(labels)
ax.legend(loc='best')

Example of the data I am working with.

Object,Metric,Length
MT1,B2A1,3.57675
MT1,B2A2,2.9474600000000004
MT1,B2A3,2.247772857142857
MT1,B2A4,3.754455
MT1,B2A5,2.716282
MT1,B2A6,2.91325
MT10,B2A1,3.34361
MT10,B2A2,2.889958333333333
MT10,B2A3,2.22087
MT10,B2A4,2.87669
MT10,B2A5,1.6745005555555557
MT12,B2A1,3.3938900000000003
MT12,B2A2,2.00601
MT12,B2A3,2.1720200000000003
MT12,B2A4,2.452923333333333
1
Where do you call ax.legend() in your main code? - Guimoute
Thanks for noting! I missed adding it to the example. I call legend after setting the xticklabels. - Christer Edvardsson
so what are header1 and header2? Metric and Length? - Roim
Yes, exactly! I though it would be easier to overview if I made all the names neutral in the code. Was this a mistake? - Christer Edvardsson

1 Answers

4
votes

The no handles with labels found to put in the legend error is due to calling ax.legend() while your two artists (boxplot and swarmplot) do not have a label.

sns.boxplot is based on matplotlib's boxplot and sns.swarmplot on scatter, so all you need is to give them respectively a labels and label argument.

ax = sns.boxplot(..., labels=["Metric", "Length"])
ax = sns.swarmplot(..., label="something goes here")

Alternatively, according to this you can leave the seaborn part untouched and fiddle with:

handles, _ = ax.get_legend_handles_labels()          # Get the artists.
ax.legend(handles, ["label1", "label2"], loc="best") # Associate manually the artists to a label.