wiscoYogi
wiscoYogi

Reputation: 365

bar chart legend based on coloring of bars by group not value

I've created a bar chart as described here where I have multiple variables (indicated in the 'value' column) and they belong to repeat groups. I've colored the bars by their group membership.

I want to create a legend ultimately equivalent to the colors dictionary, showing the color corresponding to a given group membership.

Code here:

d = {'value': [1, 2, 4, 5, 7 ,10], 'group': [1, 2, 3, 2, 2, 3]}
df = pd.DataFrame(data=d)
colors = {1: 'r', 2: 'b', 3: 'g'}
df['value'].plot(kind='bar', color=[colors[i] for i in df['group']])
plt.legend(df['group'])

In this way, I just get a legend with one color (1) instead of (1, 2, 3).

Thanks!

Upvotes: 1

Views: 1686

Answers (2)

JohanC
JohanC

Reputation: 80329

With pandas, you could create your own legend as follows:

from matplotlib import pyplot as plt
from matplotlib import patches as mpatches
import pandas as pd

d = {'value': [1, 2, 4, 5, 7 ,10], 'group': [1, 2, 3, 2, 2, 3]}
df = pd.DataFrame(data=d)
colors = {1: 'r', 2: 'b', 3: 'g'}
df['value'].plot(kind='bar', color=[colors[i] for i in df['group']])

handles = [mpatches.Patch(color=colors[i]) for i in colors]
labels = [f'group {i}' for i in colors]
plt.legend(handles, labels)

plt.show()

result

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150735

You can use sns:

sns.barplot(data=df, x=df.index, y='value', 
            hue='group', palette=colors, dodge=False)

Output:

enter image description here

Upvotes: 1

Related Questions