pythonic生物人

Python seaborn超级细节篇-使用palette

本文分享Python seaborn中通过配色palette美化图形。配色(palette),用于设置color palette,例如,Set1、#a1c9f4、red等。

内容很多,本文展示部分,对完整内容感兴趣见文末,快速浏览一下,
Image

5.3 palette设置图形配色

设置图形配色palette目的在于有效地展示数据、让图表吸引人,seaborn调色板palette可分为3大类:

  • 定性调色板(qualitative palettes):适用于分类数据(categorical data),例如,一项调查中的满意度评级(“非常不满意”,“不满意”,“中立”,“满意”,“非常满意”)中人员占比数据,例如,

ImageImage

  • 顺序调色板(sequential palettes):适用于数值数据(numeric data),例如,一周中每天温度值数据,例如,

ImageImage

  • 离散调色板(diverging palettes):适用于在数值数据中表示具有分类边界的情况(numeric data with a categorical boundary),例如,小编粉丝中12-18岁、19-24岁、25-35岁各区间人员占比数据。

ImageImage

seaborn提供多种配色设置函数,但是,容易让初学者无从下手,下文将从以3个方面详细介绍:

  • 颜色构建
  • 交互式选色器
  • 颜色设置

5.3.1 构建颜色

5.3.1.1 cubehelix_palette

基于cubehelix系统使用cubehelix_palette函数构建sequential palettes,生成一个亮度线性递减(或递增)的colormap,使用该颜色生成的图形无论是打印成黑白图像或被色盲者观看时都依然能够清晰展现数据的不同特征。cubehelix_palette使用方法,

import seaborn as sns

cubehelix_palette_test = sns.cubehelix_palette(
    n_colors=6,  #颜色数量
    start=0,  #设置颜色的起始值(0 <= start <= 3)
    rot=0.4,  #设置颜色轮上的旋转值
    gamma=1.0,  #调整颜色的非线性以突出暗色(gamma < 1)或亮色(gamma > 1)
    hue=0.8,  #设置颜色的饱和度(0 <= hue <= 1)
    light=0.85,  #设置颜色的最暗颜色的强度(0 <= light <= 1)
    dark=0.15,  #设置颜色的最亮颜色的强度0 <= dark <= 1
    reverse=False,  #默颜色顺序,False为从亮到暗,True为从暗到亮
    as_cmap=
    False  ##False返回元组格式颜色,如[0.9312692223325372, 0.8201921796082118, 0.7971480974663592];
    #True则返回matplotlib.colors.ListedColormap
)
print(cubehelix_palette_test) #输出cubehelix_palette返回值
cubehelix_palette_test

以上输出6中颜色,Image

当参数as_cmap设置为False时,同时输出6中元组格式颜色,Image

上面的例子为了介绍cubehelix_palette的各个参数,参数全部列出,会让使用者感觉参数很多,使用不友好,其实,实际使用时,只需要修改个别参数,大部分都可以直接使用默认值。例如,Image

Image
5.3.1.9.2 n_colors参数

除了palette参数,还需要注意的是n_colors参数,当n_colors=None时,color_palette输出palette参数指定调色盘最大数量颜色(palette_n_colors),根据n_colors设置数量总共有以下情况:

  • n_colors=None,color_palette输出palette中所有颜色;
  • n_colors<palette_n_colors,color_palette输出palette中的n_colors种颜色;
  • n_colors>palette_n_colors,color_palette输出palette中的所有颜色+palette中的前(n_colors-palette_n_colors)种颜色,即此时会循环输出palette中颜色;
Image

5.3.2 交互式选色器

seaborn提供了交互式选色器,帮助预览各种colormap,结合5.3.1章节中的各种颜色构建方法可以快速挑选合适的colormap,本节详细介绍各个选色器的使用。


5.3.2.1 choose_colorbrewer_palette

启动交互式小部件,从ColorBrewer中挑选colormap,这些colormap都包含在5.3.1.4章节的mpl_palette中。choose_colorbrewer_palette使用方法,

import seaborn as sns

sns.choose_colorbrewer_palette(
    data_type,  # data_type有‘sequential’, ‘diverging’, ‘qualitative’三种可选
    as_cmap=False)

在jupyter notebook中执行代码,启动如下交互式小部件,当data_type设置为‘sequential’时,效果如下,Image

通过鼠标拖动修改参数,快速查看不同colormap效果。当data_type设置为‘qualitative’时,Image

当data_type设置为‘diverging’时,Image


5.3.3 设置颜色

5.3.3.1 绘图函数中palette设置

如sns.boxplot(palette=palette)中的palette参数,

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

fig, axs = plt.subplots(2, 2, figsize=(10, 8))

data = {f'Group {i}': np.random.normal(i, 1, 100) for i in range(1, 5)}
df = pd.DataFrame(data)

# 设置不同的调色板
palettes = [
    "bright",  #使用章节5.3.1.9 color_palette方法
    ["#efefef", "#e9f3ea", "#d4dee7", "#f8f2e4"],  #直接传入颜色
    "Blues_r",  #使用章节5.3.1.4 mpl_palette中的调色盘
    sns.light_palette("red").as_hex()  #使用章节5.3.1.3 light_palette方法
]

for ax, palette in zip(axs.flatten(), palettes):
    sns.boxplot(data=df, palette=palette, ax=ax)  #boxplot绘图函数中palette设置不同调色盘
    ax.set_title(f'Palette=: {palette}')

plt.tight_layout()
plt.show()

Image

5.3.3.2 set_palette设置颜色

此外,还可以通过set_palette设置颜色,

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

# 生成模拟数据
data = {f'Group {i}': np.random.normal(i, 1, 100) for i in range(1, 5)}
df = pd.DataFrame(data)

fig, axs = plt.subplots(2, 2, figsize=(10, 8))

# 定义不同的调色板
palettes = [
    "bright",  #使用章节5.3.1.9 color_palette方法
    ["#efefef", "#e9f3ea", "#d4dee7", "#f8f2e4"],  #直接传入颜色
    "Blues_r",  #使用章节5.3.1.4 mpl_palette中的调色盘
    sns.light_palette("red").as_hex()  #使用章节5.3.1.3 light_palette方法
]

# 绘制四个子图的箱线图,并设置不同的调色板
for ax, palette in zip(axs.flatten(), palettes):
    sns.set_palette(palette)  #set_palette设置不同的调色板
    sns.boxplot(data=df, ax=ax)
    ax.set_title(f'Palette: {palette}')

plt.tight_layout()
plt.show()

Image
-END-
节选自原创Python可视化教程(基于py可视化利器seaborn):530张图形+8000行代码+详细代码注释+后续免费更新+学习交流群,部分目录,
加入学习要趁早,随着加入学习的小伙伴越多,维护成本越来越大,月底将对价格适当调整,优惠截止于7月31日24:00。
Image
ImageImageImage
Image

每类图表包含详细代码+详细代码注释,多达8000行代码,例如,Image


如何加入学习?

👇(收费、务必备注:169)

Image

✅解锁获取6大权限:

  • 代码(复制即可运行)
  • 在线教程文档(方便后续更新)
  • 依赖数据(免费下载)
  • 微信交流群
  • 后续更新
  • 交流群定期包邮送最新统计、编程、AI类书籍