在条形图中使用色调时,让 seaborn 显示颜色条而不是图例? [英] Make seaborn show a colorbar instead of a legend when using hue in a bar plot?

查看:26
本文介绍了在条形图中使用色调时,让 seaborn 显示颜色条而不是图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我想绘制一个条形图,其中条形的色调代表一些连续的数量.例如

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')

这里的图例有点傻,我绘制的条形越多,情况就越糟.最有意义的是颜色条(例如在调用 <代码>sns.heatmap).有没有办法让seaborn做到这一点?

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?

推荐答案

另一个答案有点老套.因此,更严格的解决方案是不手动生成ScalarMappable作为颜色条的输入,而不会产生随后删除的图.

The other answer is a bit hacky. So a more stringent solution, without producing plots that are deleted afterwards, would involve the manual creation of 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)
sm.set_array([])

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)

plt.show()

这篇关于在条形图中使用色调时,让 seaborn 显示颜色条而不是图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆