【问题标题】:Avoid Seaborn barplot desaturation of colors为什么 Seaborn 条形图会使颜色去饱和?
【发布时间】:2020-07-31 00:41:10
【问题描述】:

我正在尝试使用几个不同的库(bokehseabornmatlotlib)在 Python 中制作绘图,但保持相同的配色方案。我从散景中选择了分类调色板:
from bokeh.palettes import Category10 as palette
然后还在seabornmatplotlib 中使用它。我的问题是,虽然在matplotlib 中,颜色似乎与bokeh 非常相似(如调色板中所定义),但seaborn 显示出比应有的更深的颜色(即不饱和或不饱和)。我想知道默认情况下它是否会对任何配色方案进行某种调光,以及是否有任何方法可以避免这种情况。 下面是使用不同库制作相同条形图的代码
使用bokeh

source = pd.DataFrame({'names': ['exp_1', 'exp_2'], 'data':[3, 5], 'color':palette[10][:2]})
p = bokeh.plotting.figure(x_range=['exp_1', 'exp_2'], y_range=(0,6), plot_height=500, title="test")
p.vbar(x='names', top='data', width=0.9,  legend_field="names", source=source, color='color')
p.xgrid.grid_line_color = None
p.legend.orientation = "horizontal"
p.legend.location = "top_center"
p.xaxis.major_label_text_font_size = '22pt'
p.yaxis.major_label_text_font_size = '22pt'
bokeh.io.show(p)

使用matplotlib

# same palette both for seaborn and matplotlib (taken from bokeh palette)
sns_palette=sns.color_palette(palette[10]) 
fig, ax = plt.subplots()
plt.style.use('seaborn')
ax.set_xlabel('experiment', fontsize=20)
ax.tick_params(axis='both', which='major', labelsize=22)
ax.set_xticks([0, 1])
ax.set_xticklabels(['exp_1', 'exp_2'], fontsize=18)
ax.bar([0, 1], source['data'], align='center', color=sns_palette[:2])

并使用bokeh:

plt.figure()
ax = sns.barplot(x="names", y="data", data=source, palette=sns_palette[0:2])
ax.set_xlabel('experiment', fontsize=20)
ax.tick_params(axis='both', which='major', labelsize=18)
plt.tight_layout()


散景条形图:

matplotlib 条形图

seaborn barplot:

【问题讨论】:

  • @JohanC 似乎不是原因:我检查过,使用白色背景和明确的 alpha=1 不会改变条形图的颜色:sns.set_style('white') ; kwargs = {'alpha':1}; ax = sns.barplot(x="names", y="data", data=source, palette=sns_palette[0:2], **kwargs)
  • barplot 有一个选项saturation,默认为0.75。将其设置为 1 可避免所有饱和:sns.barplot(..., saturation=1)(尽管如此,出于审美原因,文档建议进行一些去饱和)。
  • @JohanC 是的,这行得通!谢谢! (有趣的是,默认情况下,这个“去饱和”选项似乎只存在于条形图和箱线图中,而不存在于线图中)。如果您发表评论作为答案,我可以接受
  • 链接的文档解释说,建议对大面积进行去饱和,而不是对线条。

标签: python matplotlib plot seaborn palette


【解决方案1】:

Seaborn barplot 默认将条形面颜色的饱和度设置为 0.75。这可以通过在 barplot 调用中添加 saturation=1 来覆盖。

import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns

source = pd.DataFrame({'names': ['exp_1', 'exp_2'], 'data':[3, 5]})
fig, ax = plt.subplots(1, 2)

# default saruration setting
sns.barplot(x="names", y="data", data=source, ax=ax[0])
ax[0].set_title('default saturation')

# additional parameter `saturation=1` passed to barplot
sns.barplot(x="names", y="data", data=source, saturation=1, ax=ax[1])
ax[1].set_title('saturation=1')

(这个答案直接来自@JohanC 的评论,我只是将其提升为一个答案......很高兴所有权归该用户。)

【讨论】:

    猜你喜欢
    • 2012-10-30
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2022-01-11
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多