Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to relabel bars in seaborn plot?

I'd like to relabel the bars in my plot. Currently, my bars are grouped and named as "A", "B", and "C" in this toy example.

How can I relabel A, B, and C to other names, e.g., "first", "second", and "third"?

Current plot and code below: enter image description here

sns.catplot(data = data, 
            x = x,
            y = y,
            hue='condition',
            kind='bar', 
            order=['A', 'B', 'C'],
            palette=sns.color_palette(['#FF5720', '#18C288']))

Thanks so much for your advice in advance!

like image 896
psychcoder Avatar asked Sep 21 '25 06:09

psychcoder


2 Answers

Just use xticklabels inside g.set(). Example taken from here: catplot example.

import seaborn as sns
sns.set(style="whitegrid")

# Load the example Titanic dataset
titanic = sns.load_dataset("titanic")

# Draw a nested barplot to show survival for class and sex
g = sns.catplot(
        x="class", 
        y="survived", 
        hue="sex", 
        data=titanic,
        height=6, 
        kind="bar", 
        palette=sns.color_palette(['#FF5720', '#18C288'])
                )

g.despine(left=True)
g.set_ylabels("survival probability")
g.set(xticklabels=["first", "second", "third"])

Example

I would rename the labels on the fly:

fg = (
  df.replace(columns={x: {'A': 'First', 'B': 'Second', 'C': 'Third'}})
    .pipe(
      (sns.catplot, 'data'),
      x = x,
      y = y,
      hue='condition',
      kind='bar', 
      order=['First', 'Second', 'Third'],
      palette=sns.color_palette(['#FF5720', '#18C288'])
    )
)

This way, the axes labels won't get broken if the more categories end up in the dataframe

like image 31
Paul H Avatar answered Sep 22 '25 19:09

Paul H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!