Raul Guarini Riva
Raul Guarini Riva

Reputation: 795

How to specify legend based on different groups with Matplotlib or Seaborn

I have a dataset that looks like the following:

df =  {'tic': {0: 'A',
      1: 'AAPL',
      2: 'ABC',
      3: 'ABT',
      4: 'ADBE',
      5: 'ADI',
      6: 'ADM',
      7: 'ADP',
      8: 'ADSK',
      9: 'AEE'},
     'Class': {0: 'Manufacturing',
      1: 'Tech',
      2: 'Trade',
      3: 'Manufacturing',
      4: 'Services',
      5: 'Tech',
      6: 'Manufacturing',
      7: 'Services',
      8: 'Services',
      9: 'Electricity and Transportation'},
     'Color': {0: 'blue',
      1: 'teal',
      2: 'purple',
      3: 'blue',
      4: 'red',
      5: 'teal',
      6: 'blue',
      7: 'red',
      8: 'red',
      9: 'orange'},
     'Pooled 1': {0: 0.0643791550056838,
      1: 0.05022103288830682,
      2: 0.039223739393748916,
      3: 0.036366693834970217,
      4: 0.05772708899447428,
      5: 0.05969899935101172,
      6: 0.04568101605219955,
      7: 0.04542272002937567,
      8: 0.07138013872431757,
      9: 0.029987722053015278}}

I want to produce a bat plot with the values stored in Pooled 1. But I would like to color the bars with the colors stored in Color. All bars of the same Class should have the same color and should be plotted together. I am only showing part of the dataset above.

The code I am using is the following:

fig, axs = plt.subplots(1,1,figsize = (24, 5))
tmp_df = df.sort_values('Class')
plt.bar(np.arange(len(df)), tmp_df['Pooled 1'], color = tmp_df['Color'])

It produces almost the desired output: enter image description here

I would like to have a legend with the names in Class and the colors from Color. I know that seaborn can do that with barplot but then it won't follow the desired colors. And I don't know why but barplot takes a long time to plot the dataset. Matplotlib is super quick though.

What's the best way to add a legend in this case? Thanks in advance!

Upvotes: 1

Views: 420

Answers (1)

JohanC
JohanC

Reputation: 80574

You can assign a label to the first bar of each class. Matplotlib will use these labels to create a legend:

from matplotlib import pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({'tic': {0: 'A', 1: 'AAPL', 2: 'ABC', 3: 'ABT', 4: 'ADBE', 5: 'ADI', 6: 'ADM', 7: 'ADP', 8: 'ADSK', 9: 'AEE'}, 'Class': {0: 'Manufacturing', 1: 'Tech', 2: 'Trade', 3: 'Manufacturing', 4: 'Services', 5: 'Tech', 6: 'Manufacturing', 7: 'Services', 8: 'Services', 9: 'Electricity and Transportation'}, 'Color': {0: 'blue', 1: 'teal', 2: 'purple', 3: 'blue', 4: 'red', 5: 'teal', 6: 'blue', 7: 'red', 8: 'red', 9: 'orange'}, 'Pooled 1': {0: 0.0643791550056838, 1: 0.05022103288830682, 2: 0.039223739393748916, 3: 0.036366693834970217, 4: 0.05772708899447428, 5: 0.05969899935101172, 6: 0.04568101605219955, 7: 0.04542272002937567, 8: 0.07138013872431757, 9: 0.029987722053015278}})
fig, ax = plt.subplots(1, 1, figsize=(14, 5))
tmp_df = df.sort_values('Class')
bars = ax.bar(tmp_df['tic'], tmp_df['Pooled 1'], color=tmp_df['Color'])
prev = None
for cl, color, bar in zip(tmp_df['Class'], tmp_df['Color'], bars):
    if cl != prev:
        bar.set_label(cl)
        prev = cl
ax.margins(x=0.01)
ax.legend(title='Class', bbox_to_anchor=(1.01, 1.01), loc='upper left')
plt.tight_layout()
plt.show()

bar plot with legend per class

PS: Note that you could also use Seaborn and let the coloring go automatic:

import seaborn as sns

sns.barplot(data=tmp_df, x='tic', y='Pooled 1', hue='Class', palette='tab10', dodge=False, saturation=1, ax=ax)

sns.barplot colored via class

Upvotes: 2

Related Questions