Matplotlib 第五章 样式色彩秀芳华

一.绘图样式(style)

1.Matplotlib预先定义样式

Matplotlib 提供了大量开箱即用的内置样式,只需一行代码即可全局生效,无需逐图调整。

(1)基础用法

复制代码
import matplotlib.pyplot as plt
# 调用默认样式
plt.style.use('default')
# 绘制图表
plt.plot([1,2,3,4], [2,3,4,5])
plt.show()
  • default:Matplotlib 原生默认样式,白底蓝线、简洁无网格。
  • ggplot:复刻 R 语言 ggplot2 风格,浅灰底、网格线、配色更柔和。

(2) 全部内置样式列表

通过 print(plt.style.available) 可查看所有支持的样式,共 26 种(不同版本略有差异):

复制代码
['Solarize_Light2', '_classic_test_patch', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']

(3)常用样式速览

样式名 特点 适用场景
default 白底、蓝线、无网格 通用默认
ggplot 浅灰底、网格线、ggplot 风格 数据可视化报告
dark_background 黑底、亮色线条 夜间模式、PPT 展示
fivethirtyeight 复刻 FiveThirtyEight 网站风格,粗线条、网格 新闻类数据图表
grayscale 全灰度配色 黑白印刷
seaborn-* 系列 复刻 seaborn 库的多种风格 统计图表、论文

2.用户自定义mplstyle

当内置样式无法满足需求时,可创建自定义 .mplstyle 文件,统一配置全局样式参数。

(1) 步骤 1:创建样式文件

在任意路径下新建文件(如 presentation.mplstyle),写入样式配置:

复制代码
# 标题字号
axes.titlesize : 24
# 坐标轴标签字号
axes.labelsize : 20
# 线条宽度
lines.linewidth : 3
# 标记点大小
lines.markersize : 10
# X轴刻度字号
xtick.labelsize : 16
# Y轴刻度字号
ytick.labelsize : 16

(2)步骤 2:调用自定义样式

复制代码
# 替换为你的文件实际路径
plt.style.use('file/presentation.mplstyle')
plt.plot([1,2,3,4], [2,3,4,5])
plt.show()
  • 效果:线条变粗、字号放大,适合汇报、PPT 展示。

(3)混合样式(多样式叠加)

Matplotlib 支持列表形式传入多个样式 ,实现样式叠加,右侧样式会覆盖左侧同名参数

示例:深色背景 + 自定义汇报样式

复制代码
# 先应用 dark_background,再用自定义样式覆盖字号、线宽等参数
plt.style.use(['dark_background', 'file/presentation.mplstyle'])
plt.plot([1,2,3,4], [2,3,4,5])
plt.show()
  • 效果:黑底、亮线、粗线条、大字号,完美适配夜间 PPT 展示。

注:

  1. 样式生效范围plt.style.use()全局生效,调用后所有后续绘图都会应用该样式,无需重复设置。
  2. 样式优先级 :混合样式中,列表越靠后,优先级越高,同名参数会被右侧样式覆盖。
  3. 临时恢复默认 :若需临时切换样式,可通过 plt.style.use('default') 重置。
  4. 自定义样式路径 :若将 .mplstyle 文件放入 Matplotlib 的 stylelib 目录,可直接通过样式名调用(无需写完整路径)。
  5. 参数配置参考 :完整可配置参数可参考 Matplotlib 官方 rcParams 文档,涵盖字体、颜色、网格、图例等所有细节。

3.设置rcparams

Matplotlib 的所有默认样式参数都保存在 matplotlib.rcParams 字典中,通过修改它可以在运行时动态全局生效,影响后续所有绘图。

(1)基础用法:单参数修改

复制代码
import matplotlib as mpl
import matplotlib.pyplot as plt

# 先恢复默认样式,作为基准
plt.style.use('default')
plt.plot([1,2,3,4], [2,3,4,5])
plt.show()
  • 效果:默认白底、实线、细蓝线,无网格。

    单独修改线条宽度和线型

    mpl.rcParams['lines.linewidth'] = 2
    mpl.rcParams['lines.linestyle'] = '--'
    plt.plot([1,2,3,4], [2,3,4,5])
    plt.show()

  • 效果:线条变粗,变为虚线,全局生效。

(2)便捷用法:批量修改(按分组)

Matplotlib 提供 mpl.rc() 方法,可按参数分组一次性修改多个同组参数,代码更简洁:

复制代码
# 一次性修改 lines 分组下的线宽和线型
mpl.rc('lines', linewidth=4, linestyle='-.')
plt.plot([1,2,3,4], [2,3,4,5])
plt.show()
  • 效果:线条更粗,变为点划线,全局生效。
  • 全局生效 :修改 rcParams 后,所有后续绘图都会应用该设置,直到程序结束或手动重置。
  • 参数分组 :参数按 分组.参数名 命名,如 lines.linewidthaxes.titlesizextick.labelsize 等。
  • 临时重置 :可通过 plt.rcdefaults() 一键恢复所有 rc 参数到出厂默认。
  • 优先级rcParams 修改的优先级高于内置样式,低于绘图时的逐图手动设置 (如 plt.plot(..., linewidth=5) 会覆盖 rcParams)。

4. 永久修改:matplotlibrc 配置文件

如果希望永久修改默认样式 (每次运行 Matplotlib 都生效),可以直接编辑 matplotlibrc 配置文件,这是 Matplotlib 所有默认样式的源头。

(1)步骤 1:找到配置文件路径

复制代码
import matplotlib as mpl
# 打印 matplotlibrc 文件的绝对路径
print(mpl.matplotlib_fname())
  • 输出示例(不同系统路径不同):

    复制代码
    /usr/local/lib/python3.10/site-packages/matplotlib/mpl-data/matplotlibrc

    或用户目录下的自定义路径:~/.config/matplotlib/matplotlibrc(Linux/macOS)、C:\Users\用户名\.matplotlib\matplotlibrc(Windows)。

(2)步骤 2:编辑配置文件

打开 matplotlibrc 文件,它是一个纯文本文件,包含了所有可配置参数(默认大多被 # 注释)。

  • 找到需要修改的参数,去掉 # 注释,修改对应值即可,例如:

    复制代码
    # 线条默认宽度
    lines.linewidth: 8
    # 线条默认线型
    lines.linestyle: -
    # 标题字号
    axes.titlesize: 24
    # 坐标轴标签字号
    axes.labelsize: 20
  • 保存文件后,重启 Python 环境,所有新绘图都会永久应用这些修改。

  • 生效范围 :修改 matplotlibrc系统级 / 用户级永久生效,所有 Python 环境、所有脚本都会应用该样式。
  • 优先级matplotlibrc 是最低优先级,会被 rcParams 动态修改、plt.style.use()、逐图手动设置覆盖。
  • 备份建议:修改前建议先备份原文件,避免误改导致样式异常。
  • 用户级 vs 系统级 :优先修改用户目录下的 matplotlibrc,避免影响系统全局环境;升级 Matplotlib 时,系统级文件会被覆盖,用户级文件不受影响。

二.色彩设置(color)

在可视化中,颜色可拆解为三个视觉通道,不同通道适用场景不同:

  • 色相:无明显顺序性,用于区分类别数据(如不同产品、不同组别)
  • 明度 / 亮度:有明确视觉优先级,用于表达数据大小、顺序
  • 饱和度:同样可区分优先级,常与明度配合使用

1. RGB / RGBA 浮点元组

[0,1] 区间的浮点数表示颜色,4 个分量依次为 (红, 绿, 蓝, 透明度alpha),alpha 可省略。

复制代码
# 纯RGB(不透明)
plt.plot([1,2,3], [4,5,6], color=(0.1, 0.2, 0.5))
# RGBA(半透明,alpha=0.5)
plt.plot([4,5,6], [1,2,3], color=(0.1, 0.2, 0.5, 0.5))
  • 特点:精准控制颜色,适合自定义配色,alpha 可实现叠加效果

2. HEX 十六进制颜色码

用网页标准的十六进制字符串表示,格式为 #RRGGBB#RRGGBBAA(最后两位为透明度)。

复制代码
# 纯RGB(不透明,浅灰色)
plt.plot([1,2,3], [4,5,6], color='#0f0f0f')
# RGBA(半透明,alpha=0x80≈0.5)
plt.plot([4,5,6], [1,2,3], color='#0f0f0f80')
  • 特点:和前端、设计工具无缝衔接,适合复用设计稿配色

3. 灰度色阶

[0,1] 区间的字符串表示灰度,'0' 为纯黑,'1' 为纯白。

复制代码
# 50%灰度
plt.plot([1,2,3], [4,5,6], color='0.5')
  • 特点:适合黑白印刷、灰度可视化,代码简洁

4. 单字符基本颜色

Matplotlib 内置 8 个单字符基础色,对应英文缩写:

单字符 英文 中文
b blue 蓝色
g green 绿色
r red 红色
c cyan 青色
m magenta 品红
y yellow 黄色
k black 黑色
w white 白色
复制代码
# 品红色线条
plt.plot([1,2,3], [4,5,6], color='m')
  • 特点:快速调用,适合简单绘图

5. 标准颜色名称

Matplotlib 支持 CSS4 标准颜色名、Tableau 调色板名,可直接用字符串调用。

复制代码
# 棕褐色(tan)线条
plt.plot([1,2,3], [4,5,6], color='tan')
# Tableau 调色板
plt.plot([1,2,3], [4,5,6], color='tab:blue')
  • 特点:语义化强,可读性高,内置完整颜色对照表

(1)Tableau 标准调色板

颜色名称 对应代码 视觉特点 适用场景
tab:blue tab:blue 标准商务蓝 主数据系列、默认首选
tab:orange tab:orange 暖调橙色 对比系列、次数据
tab:green tab:green 正向绿色 成功、增长类数据
tab:red tab:red 警示红色 异常、下降类数据
tab:purple tab:purple 柔和紫色 强调、辅助系列
tab:brown tab:brown 稳重棕色 中性、背景系列
tab:pink tab:pink 柔和粉色 女性相关、柔和对比
tab:gray tab:gray 中性灰色 次要、参考线
tab:olive tab:olive 橄榄绿 自然、环境类数据
tab:cyan tab:cyan 亮青色 科技、冷调数据

(2)CSS 标准颜色表(完整整理)

(a)黑白灰系列
颜色名称 对应代码 灰度值参考
black black 纯黑
dimgray / dimgrey dimgray / dimgrey 深灰
gray / grey gray / grey 中灰
darkgray / darkgrey darkgray / darkgrey 暗灰
silver silver 银灰
lightgray / lightgrey lightgray / lightgrey 浅灰
gainsboro gainsboro 极浅灰
whitesmoke whitesmoke 烟白
white white 纯白
snow snow 雪白

(b) 红 / 粉 / 棕系列

颜色名称 对应代码 视觉特点
rosybrown rosybrown 玫瑰棕
lightcoral lightcoral 浅珊瑚
indianred indianred 印度红
brown brown 棕色
firebrick firebrick 砖红
maroon maroon 栗色
darkred darkred 深红
red red 纯红
mistyrose mistyrose 雾玫瑰
salmon salmon 三文鱼粉
tomato tomato 番茄红
darksalmon darksalmon 深三文鱼
coral coral 珊瑚橙
orangered orangered 橙红
lightsalmon lightsalmon 浅三文鱼
sienna sienna 赭石
seashell seashell 贝壳白
chocolate chocolate 巧克力棕
saddlebrown saddlebrown 马鞍棕
sandybrown sandybrown 沙棕
peachpuff peachpuff 桃粉
peru peru 秘鲁棕
linen linen 亚麻白
crimson crimson 深红
pink pink 粉色
lightpink lightpink 浅粉
hotpink hotpink 亮粉
deeppink deeppink 深粉
palevioletred palevioletred 浅紫红
lavenderblush lavenderblush 淡紫粉
mediumvioletred mediumvioletred 中紫红
orchid orchid 兰花紫
magenta / fuchsia magenta / fuchsia 品红
darkmagenta darkmagenta 深品红
purple purple 纯紫
violet violet 紫罗兰
plum plum 李子紫
thistle thistle 蓟紫
mediumorchid mediumorchid 中兰花紫
darkviolet darkviolet 深紫
darkorchid darkorchid 深兰花紫
indigo indigo 靛蓝

(c) 橙 / 黄 / 米白系列

颜色名称 对应代码 视觉特点
bisque bisque 陶土白
darkorange darkorange 深橙
burlywood burlywood 原木棕
antiquewhite antiquewhite 古董白
tan tan 棕褐色
navajowhite navajowhite 纳瓦霍白
blanchedalmond blanchedalmond 杏仁白
papayawhip papayawhip 木瓜白
moccasin moccasin 鹿皮白
orange orange 纯橙
wheat wheat 小麦色
oldlace oldlace 蕾丝白
floralwhite floralwhite 花卉白
darkgoldenrod darkgoldenrod 深金棕
goldenrod goldenrod 金棕
cornsilk cornsilk 玉米丝白
gold gold 金色
lemonchiffon lemonchiffon 柠檬纱白
khaki khaki 卡其色
palegoldenrod palegoldenrod 浅金棕
darkkhaki darkkhaki 深卡其
ivory ivory 象牙白
beige beige 米色
lightyellow lightyellow 浅黄
lightgoldenrodyellow lightgoldenrodyellow 浅金棕黄
olive olive 橄榄绿
yellow yellow 纯黄
olivedrab olivedrab 橄榄褐
yellowgreen yellowgreen 黄绿
darkolivegreen darkolivegreen 深橄榄绿
greenyellow greenyellow 绿黄
chartreuse chartreuse 查特酒绿
lawngreen lawngreen 草坪绿
honeydew honeydew 蜜瓜白
darkseagreen darkseagreen 深海草绿
palegreen palegreen 浅绿
lightgreen lightgreen 亮绿

(d)绿 / 青 / 蓝系列

颜色名称 对应代码 视觉特点
forestgreen forestgreen 森林绿
limegreen limegreen 酸橙绿
darkgreen darkgreen 深绿
green green 纯绿
lime lime 亮绿
seagreen seagreen 海草绿
mediumseagreen mediumseagreen 中海草绿
springgreen springgreen 春绿
mintcream mintcream 薄荷白
mediumspringgreen mediumspringgreen 中春绿
mediumaquamarine mediumaquamarine 中碧色
aquamarine aquamarine 碧色
turquoise turquoise 绿松石
lightseagreen lightseagreen 浅海草绿
mediumturquoise mediumturquoise 中绿松石
azure azure 天蓝白
lightcyan lightcyan 浅青
paleturquoise paleturquoise 浅绿松石
darkslategray / darkslategrey darkslategray / darkslategrey 深石板灰
teal teal 水鸭绿
darkcyan darkcyan 深青
aqua / cyan aqua / cyan 纯青
darkturquoise darkturquoise 深绿松石
cadetblue cadetblue 军校蓝
powderblue powderblue 粉末蓝
lightblue lightblue 浅蓝
deepskyblue deepskyblue 深天蓝
skyblue skyblue 天蓝
lightskyblue lightskyblue 亮天蓝
steelblue steelblue 钢蓝
aliceblue aliceblue 爱丽丝蓝
dodgerblue dodgerblue 道奇蓝
lightslategray / lightslategrey lightslategray / lightslategrey 浅石板灰
slategray / slategrey slategray / slategrey 石板灰
slategrey slategrey 石板灰
lightsteelblue lightsteelblue 浅钢蓝
cornflowerblue cornflowerblue 矢车菊蓝
royalblue royalblue 皇家蓝
ghostwhite ghostwhite 幽灵白
lavender lavender 薰衣草紫
midnightblue midnightblue 午夜蓝
navy navy 海军蓝
darkblue darkblue 深蓝
mediumblue mediumblue 中蓝
blue blue 纯蓝
slateblue slateblue 石板蓝
darkslateblue darkslateblue 深石板蓝
mediumslateblue mediumslateblue 中石板蓝
mediumpurple mediumpurple 中紫
rebeccapurple rebeccapurple 丽贝卡紫
blueviolet blueviolet 蓝紫

6.Colormap:批量设置一组颜色

当需要用一组颜色表达数据关系时,使用 colormap(颜色映射),Matplotlib 将其分为 5 大类:

类型 特点 适用场景 示例
顺序型 (Sequential) 单一色调,明度 / 饱和度渐变 有顺序的数值数据(如温度、销量) RdPuviridisBlues
发散型 (Diverging) 两种颜色从中间向两端渐变 有中间基准的数据(如正负偏差、地形) coolwarmRdBu
循环型 (Cyclic) 首尾颜色一致,中间过渡 环形 / 周期性数据(如角度、时间) twilighthsv
定性型 (Qualitative) 杂色、无渐变 无顺序的类别数据(如不同组别) tab10Set2
杂色型 (Miscellaneous) 特定场景专用 特殊可视化(如彩虹、地形) rainbowterrain

示例:散点图使用 colormap

复制代码
import numpy as np
import matplotlib.pyplot as plt

x = np.random.randn(50)
y = np.random.randn(50)
# c=x 表示用x值映射颜色,cmap指定颜色映射
plt.scatter(x, y, c=x, cmap='RdPu')
plt.show()
  • 效果:点的颜色随 x 值从浅粉到深紫渐变,直观表达数据大小

    import matplotlib.pyplot as plt
    import numpy as np

    1. 单颜色设置示例

    plt.style.use('default')

    RGB

    plt.plot([1,2,3], [4,5,6], color=(0.1, 0.2, 0.5), label='RGB')

    HEX

    plt.plot([4,5,6], [1,2,3], color='#0f0f0f80', label='HEX')

    灰度

    plt.plot([1,2,3], [1,2,3], color='0.5', label='灰度')

    单字符

    plt.plot([4,5,6], [4,5,6], color='m', label='单字符m')

    颜色名

    plt.plot([1,3,5], [2,4,6], color='tan', label='颜色名tan')
    plt.legend()
    plt.show()

    2. Colormap 示例

    x = np.random.randn(50)
    y = np.random.randn(50)
    plt.scatter(x, y, c=x, cmap='RdPu', s=100)
    plt.colorbar(label='x值')
    plt.show()

相关推荐
书到用时方恨少!18 小时前
Python Matplotlib 使用指南:数据可视化的画笔
python·信息可视化·matplotlib
人工干智能2 天前
科普:%%matplotlib inline:魔法命令 (Cell Magic)
python·matplotlib
绛橘色的日落(。・∀・)ノ4 天前
Matplotlib 第四章 文字图例尽眉目
matplotlib
喝凉白开都长肉的大胖子5 天前
在 Matplotlib 中fontweight一般怎么设置
python·matplotlib
绛橘色的日落(。・∀・)ノ5 天前
Matplotlib 第三章 布局格式定方圆
matplotlib
绛橘色的日落(。・∀・)ノ6 天前
Matplotlib 第二章 艺术画笔见乾坤
matplotlib
MediaTea10 天前
人工智能通识课:Matplotlib 绘图基础
人工智能·matplotlib
MediaTea12 天前
Matplotlib 常用函数手册
matplotlib