4

I'm trying to use Seaborn to present a 1d dataframe as a horizontal bar graph. I would like to shade the bars using the coolwarm palette to reflect their magnitude and direction.

In other words, I'm hoping to generate something like the second example shown here (this is from the Seaborn site), but I want to orient it horizontally:

enter image description here

I've succeeded in turning the graph sideways, but I can't seem to make the palette apply along the horizontal axis as well. My code:

import pandas as pd, seaborn as sns

sns.set()
df = pd.DataFrame([7,-5,-2,1.5,-3],
                  index=['question 1','question 2','question 3','question 4','question 5'],
                  columns=['t'])
sns.barplot(data=    df,
            x=       't', 
            y=       df.index,
            palette= 'coolwarm') 

The output:

output

I'd like it to go from blue to red as you move from left to right (instead of top to bottom).

0

3 Answers 3

5

Seaborn does not perform any true colormapping. So if that is desiered, one would need to do it externally. In the following, each bar gets its color from a colormap according to its magnitude.

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

sns.set()
df = pd.DataFrame([7,-5,-2,1.5,-3],
                  index=['question 1','question 2','question 3','question 4','question 5'],
                  columns=['t'])

absmax = np.abs(df["t"].values).max()
norm = plt.Normalize(-absmax, absmax)
cmap = plt.get_cmap("coolwarm")
colors = cmap(norm(df["t"].values))
plt.barh("index", "t", data=df.reset_index(), color=colors)

plt.colorbar(plt.cm.ScalarMappable(norm, cmap))

plt.gca().invert_yaxis()
plt.tight_layout()
plt.show()

enter image description here

1
  • This is exactly what I was looking for. Thanks for your response.
    – Max
    Commented Aug 22, 2019 at 10:19
3

If you don't mind having the questions in order of increasing value, you can do the following:

df2 = df.sort_values('t')

sns.barplot(data=df2,
            x='t',
            y=df2.index
            palette='coolwarm_r')

Which should yield:

enter image description here

If you want to leave your questions in their original order, you can specify a custom palette (list of RGBA values) for sns.barplot using the palette kwarg:

val_order = df['t'].rank(method='max').astype(int) # rank ordered values in column 't'
val_index = val_order - 1 # convert for use as a list index
colors = sns.color_palette('coolwarm_r', len(df.index)) # list of N colors spaced along coolwarm
palette = [colors[x] for x in val_index] # re-order colors with increasing value of 't'

sns.barplot(data=df, x='t', y=df.index, palette=palette)

Yielding:

enter image description here

After making the images I realized I accidentally used coolwarm_r instead of coolwarm. Adding the _r suffix will use a reversed colormap. Oh well.

4
  • Thank you! However, in both of these solutions, it seems like the shade of color corresponds to the item's position in the sorting, not its actual magnitude. Since my actual data are not this evenly distributed, I'd like to have the shade of color reflect their magnitude (for example, questions 3 and 4 should both appear more or less gray).
    – Max
    Commented Aug 22, 2019 at 3:16
  • The second option chooses the color based on the value in the column 't'. You could use any other column in the data frame as well, e.g. assign a magnitude column, and use that for choosing the color: df.assign(magnitude=lambda x: abs(x['t']))
    – jonchar
    Commented Aug 22, 2019 at 3:24
  • Are you sure? After playing with it some more, it really looks like it is choosing the color based on the ranked t values and not the t values themselves. Note that the line colors = sns.color_palette('coolwarm_r', len(df.index)) generates a list of evenly-spaced colors that are then assigned listwise to the palette in the following line.
    – Max
    Commented Aug 22, 2019 at 4:03
  • I see what you mean. You are correct. In that case I think you can use a matplotlib colormap to generate the RGBA values passed to the palette kwarg. Also see colormap normalization.
    – jonchar
    Commented Aug 22, 2019 at 15:17
1

This is going to be an extremely late reply, however...

The easiest way would be to set the hue argument as the column you wish to set as an axis for coloring:

sns.barplot(data=df,x='t',y=df.index,palette='coolwarm', hue='t', dodge=False)

It's crucial to set dodge to True since you'll get extremely thin, line-like boxes otherwise.

And you'll get this kind of output:

Output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.