Coquelicot
Coquelicot

Reputation: 9093

Make seaborn show a colorbar instead of a legend when using hue in a bar plot?

Let's say I want to make a bar plot where the hue of the bars represents some continuous quantity. e.g.

import seaborn as sns
titanic = sns.load_dataset("titanic")
g = titanic.groupby('pclass')
survival_rates = g['survived'].mean()
n = g.size()
ax = sns.barplot(x=n.index, y=n,
           hue=survival_rates, palette='Reds',
            dodge=False,
          )
ax.set_ylabel('n passengers')

bar plot drawn by sns

The legend here is kind of silly, and gets even worse the more bars I plot. What would make most sense is a colorbar (such as are used when calling sns.heatmap). Is there a way to make seaborn do this?

Upvotes: 21

Views: 17696

Answers (2)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

This answer is inefficient because it produces a plot, which is then deleted.

Instead, create a ScalarMappable as input for the colorbar.

import matplotlib.pyplot as plt
import seaborn as sns
titanic = sns.load_dataset("titanic")
g = titanic.groupby('pclass')
survival_rates = g['survived'].mean()
n = g.size()

norm = plt.Normalize(survival_rates.min(), survival_rates.max())
sm = plt.cm.ScalarMappable(cmap="Reds", norm=norm)

ax = sns.barplot(x=n.index, y=n, hue=survival_rates, palette='Reds', 
                 dodge=False)

ax.set_ylabel('n passengers')
ax.get_legend().remove()
ax.figure.colorbar(sm, ax=ax)

plt.show()

enter image description here

Upvotes: 37

Scott Boston
Scott Boston

Reputation: 153460

You can try this:

import matplotlib.pyplot as plt
import seaborn as sns
titanic = sns.load_dataset("titanic")
g = titanic.groupby('pclass')
survival_rates = g['survived'].mean()
n = g.size()

plot = plt.scatter(n.index, n, c=survival_rates, cmap='Reds')
plt.clf()
plt.colorbar(plot)
ax = sns.barplot(x=n.index, y=n, hue=survival_rates, palette='Reds', dodge=False)
ax.set_ylabel('n passengers')
ax.legend_.remove()

Output: enter image description here

Upvotes: 7

Related Questions