Seaborn - change bar color according to x name instead of hue?

843 views Asked by At

For example:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
sns.set_style('darkgrid')
fig, ax = plt.subplots()

a = pd.DataFrame({'Program': ['A', 'A', 'B', 'B', 'Total', 'Total'],
                  'Scenario': ['X', 'Y', 'X', 'Y', 'X', 'Y'],
                  'Duration': [4, 3, 5, 4, 9, 7]})

g = sns.barplot(data=a, x='Scenario', y='Duration',
                hue='Program', ci=None)

enter image description here

I want x=X and x=Y have different color, but same color for each hue(A, B, Total ...) . ( There may be more Scenario than two ) . How do I change bar color according to x name instead of hue ?

1

There are 1 answers

0
Patrick FitzGerald On

I am not aware of any straightforward way to set the colors like that using sns.barplot. Here is how can do this using pandas instead:

import pandas as pd    # v 1.1.3
import seaborn as sns  # v 0.11.0
sns.set_style('darkgrid')

# Create sample dataset
a = pd.DataFrame({'Program': ['A', 'A', 'B', 'B', 'Total', 'Total'],
                  'Scenario': ['X', 'Y', 'X', 'Y', 'X', 'Y'],
                  'Duration': [4, 3, 5, 4, 9, 7]})

# Pivot table and plot data in a bar chart
a_pivot = a.pivot(index='Scenario', columns='Program')
ax = a_pivot.plot.bar(color=[['tab:blue', 'tab:orange']], rot=0,
                      legend=None, figsize=(8,5))

# Format labels and ticks
ax.set_xlabel('Scenario', labelpad=10, size=14)
ax.set_ylabel('Duration', labelpad=20, size=14)
ax.tick_params(axis='both', labelsize=12)

pd_bar_color