Ed Jefferies
Ed Jefferies

Reputation: 209

Have colors in a seaborn bar plot match the labels in the axis

I have a bar plot generated using seaborn in python as below:

enter image description here

The x axis will always contain colors. Is there a simple way that I can get the colors of the bars to match the colors on the x axis?

my code so far:

plt.figure(figsize=(12,8))
slippers_plot = sns.barplot(data=slipper_colour,x='colour', y='total_units', palette='bright')
slippers_plot
slippers_plot.set_title("Top Slipper Colors", fontsize=20, pad=30, fontdict={"weight": "bold"})
slippers_plot.set_xlabel("Total Units", fontsize=16)
slippers_plot.set_ylabel("", fontsize=18)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)

Upvotes: 2

Views: 2419

Answers (1)

JohanC
JohanC

Reputation: 80279

If you are happy with how web colors are named you can just use the x-values for the palette:

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

slipper_colour = pd.DataFrame({'colour': ['Green', 'Black', 'Brown', 'Gray'],
                               'total_units': np.random.randint(10, 50, 4)})

plt.figure(figsize=(12, 8))
ax = sns.barplot(data=slipper_colour, x='colour', y='total_units', hue='colour', palette=slipper_colour['colour'], dodge=False)
ax.set_title("Top Slipper Colors", fontsize=20, pad=30, fontdict={"weight": "bold"})
ax.set_xlabel("Total Units", fontsize=16)
ax.set_ylabel("", fontsize=18)
ax.tick_params(labelsize=14)
plt.show()

sns.barplot colored using x-values

To fine-tune the colors, a dictionary can be used, e.g.

palette = {'Green': 'forestgreen', 'Black': 'black', 'Brown': 'sienna', 'Gray': 'silver'}

Instead of names, also hexadecimal colors (e.g. '#7B68EE') are possible.

Upvotes: 4

Related Questions