How can I combine hue and style groups in a Seaborn legend?

Viewed 984

I'm doing a Seaborn lineplot for longitudinal data which is grouped by "Subscale" using hue and by "Item" using style.

Here is my code (I hope this is understandable also without data):

ax = sns.lineplot(data = df, x = 'Week', y = 'Value', style = 'Item', hue = 'Subscale', palette = 'colorblind', markers = True)
plt.legend(bbox_to_anchor = (1.03, 1.02), fontsize = 10)

Whicht gets me this plot: enter image description here

What I want is to combine the sublegends so that it only shows the legend for "Item" but the items are colored according to "Subscale", kind of like this: enter image description here

I've failed to create this, so if any of you could help, this would be highly appreciated! Thanks :)

1 Answers

If I understand correctly, all items of a certain type have the same subscale. So, you already have (or can create) a dictionary that maps an item type to the corresponding subscale.

Seaborn creates following labels for the legend:

  • 'Subscale' for a subtitle
  • each of the subscales
  • 'Item' for a second subtitle
  • each of the items

Each label corresponds to a "handle" identifying how the marker looks like.

The following code:

  • finds the index of 'Item' to be able to split the arrays of labels and handles
  • extracts the colors of the 'Subscale's
  • applies these colors to the item markers
  • only uses the items for the legend
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

# first create some random data similar to the description
np.random.seed(123)
items = ['01', '04', '05', '06', '07', '10', '11', '13']
N = len(items)
subscale_dict = {'01': 'A', '04': 'C', '05': 'C', '06': 'C', '07': 'A', '10': 'B', '11': 'B', '13': 'A'}

df = pd.DataFrame({'Week': np.tile(np.arange(7), N),
                   'Value': np.random.rand(7 * N),
                   'Item': np.repeat(items, 7)})
df['Subscale'] = df['Item'].apply(lambda i: subscale_dict[i])
df['Subscale'] = pd.Categorical(df['Subscale'])  # creates a fixed order

# create the line plot as before
ax = sns.lineplot(data=df, x='Week', y='Value', style='Item', hue='Subscale', palette='colorblind', markers=True)

# create a dictionary mapping the subscales to their color
handles, labels = ax.get_legend_handles_labels()
index_item_title = labels.index('Item')
color_dict = {label: handle.get_color()
              for handle, label in zip(handles[1:index_item_title], labels[1:index_item_title])}

# loop through the items, assign color via the subscale of the item idem
for handle, label in zip(handles[index_item_title + 1:], labels[index_item_title + 1:]):
    handle.set_color(color_dict[subscale_dict[ label]])

# create a legend only using the items
ax.legend(handles[index_item_title + 1:], labels[index_item_title + 1:], title='Item',
          bbox_to_anchor=(1.03, 1.02), fontsize=10)

plt.tight_layout()
plt.show()

sns.lineplot with custom legend

Related