In [1]:
Copied!
# batch_colors 也支持 grid 模式、ID 列表、Collection、query_func 等所有调用方式
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from multicolor import batch_colors
# grid 模式:用原始 colors 数据绘图
@batch_colors(["Viridis", "Plasma", "Inferno"], layout="grid", cols=3)
def draw_with_hex_colors(record, ax=None):
# 将 hex 颜色列表转为 ListedColormap
cmap_obj = mcolors.ListedColormap(record["colors"])
x = np.linspace(0, 1, 256)
grad = np.tile(x, (50, 1))
ax.imshow(grad, aspect="auto", cmap=cmap_obj)
draw_with_hex_colors()
# batch_colors 也支持 grid 模式、ID 列表、Collection、query_func 等所有调用方式
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
from multicolor import batch_colors
# grid 模式:用原始 colors 数据绘图
@batch_colors(["Viridis", "Plasma", "Inferno"], layout="grid", cols=3)
def draw_with_hex_colors(record, ax=None):
# 将 hex 颜色列表转为 ListedColormap
cmap_obj = mcolors.ListedColormap(record["colors"])
x = np.linspace(0, 1, 256)
grad = np.tile(x, (50, 1))
ax.imshow(grad, aspect="auto", cmap=cmap_obj)
draw_with_hex_colors()
In [2]:
Copied!
from multicolor import cmap, batch_colors
# 名称列表方式 — 接收 record dict 而非 Colormap 对象
@batch_colors(["Viridis", "Plasma", "Inferno"])
def show_colors(record):
print(f"Name: {record['name']}")
print(f"Type: {record['cmap_type']}")
print(f"Colors (first 3): {record['colors'][:3]}")
print()
show_colors()
from multicolor import cmap, batch_colors
# 名称列表方式 — 接收 record dict 而非 Colormap 对象
@batch_colors(["Viridis", "Plasma", "Inferno"])
def show_colors(record):
print(f"Name: {record['name']}")
print(f"Type: {record['cmap_type']}")
print(f"Colors (first 3): {record['colors'][:3]}")
print()
show_colors()
Name: Viridis Type: sequential Colors (first 3): ['#440154', '#440256', '#450457'] Name: Plasma Type: sequential Colors (first 3): ['#0d0887', '#100788', '#130789'] Name: Inferno Type: sequential Colors (first 3): ['#000004', '#010005', '#010106']
@batch_colors() — 使用原始颜色数据¶
@batch_colors() 与 @batch_cmaps() 签名完全一致,但传递的是数据库原始记录 dict,包含 id、name、colors(hex 列表)、cmap_type、tags 等字段。适用于需要自定义颜色处理逻辑的场景。
3. 批量预览¶
演示如何使用 装饰器批量展示多个色带。
方式一:@batch_cmaps() — 名称列表(推荐)¶
最通用的方式,传入名称列表或 Collection。
In [3]:
Copied!
from multicolor import cmap, batch_cmaps
# 方式 1a:固定名称列表
@batch_cmaps(["Viridis", "Plasma", "Inferno"])
def show(cmap_obj):
cmap.preview(cmap_obj)
# 调用一次,自动弹出 3 个窗口
show()
from multicolor import cmap, batch_cmaps
# 方式 1a:固定名称列表
@batch_cmaps(["Viridis", "Plasma", "Inferno"])
def show(cmap_obj):
cmap.preview(cmap_obj)
# 调用一次,自动弹出 3 个窗口
show()
In [4]:
Copied!
# 方式 1b:Collection 传入
@batch_cmaps(cmap.collection(cmap_type="diverging", is_custom=False))
def show_all_diverging(cmap_obj):
cmap.preview(cmap_obj)
show_all_diverging()
# 方式 1c:查询 kwargs 直接传入
@batch_cmaps(cmap_type="sequential", limit=2)
def show_sequential(cmap_obj):
cmap.preview(cmap_obj)
show_sequential()
# 方式 1b:Collection 传入
@batch_cmaps(cmap.collection(cmap_type="diverging", is_custom=False))
def show_all_diverging(cmap_obj):
cmap.preview(cmap_obj)
show_all_diverging()
# 方式 1c:查询 kwargs 直接传入
@batch_cmaps(cmap_type="sequential", limit=2)
def show_sequential(cmap_obj):
cmap.preview(cmap_obj)
show_sequential()
方式二:@batch_cmaps() — grid 模式¶
所有色带画在一张多子图表格上。用户函数接收 ax 参数自定义绘制内容。
In [5]:
Copied!
import numpy as np
from multicolor import batch_cmaps
@batch_cmaps(colorblind_safe="any", is_custom=False, limit=6, layout="grid", cols=3)
def show_grid(cmap_obj, ax=None):
x = np.linspace(0, 1, 256)
grad = np.tile(x, (50, 1))
ax.imshow(grad, aspect="auto", cmap=cmap_obj)
show_grid()
import numpy as np
from multicolor import batch_cmaps
@batch_cmaps(colorblind_safe="any", is_custom=False, limit=6, layout="grid", cols=3)
def show_grid(cmap_obj, ax=None):
x = np.linspace(0, 1, 256)
grad = np.tile(x, (50, 1))
ax.imshow(grad, aspect="auto", cmap=cmap_obj)
show_grid()
方式二: — 按 ID 批量¶
按数据库 ID 列表批量执行。适用于从外部拿到 ID 后快速预览的场景。
In [6]:
Copied!
# 先获取几个 ID
items = cmap.list(limit=3)
print("IDs:", [item[0] for item in items])
print("Names:", [item[1] for item in items])
# 用 batch_cmaps() 按 ID 批量预览(整数列表自动识别为 ID)
@batch_cmaps([item[0] for item in items])
def show_by_id(cmap_obj):
cmap.preview(cmap_obj)
show_by_id()
# 先获取几个 ID
items = cmap.list(limit=3)
print("IDs:", [item[0] for item in items])
print("Names:", [item[1] for item in items])
# 用 batch_cmaps() 按 ID 批量预览(整数列表自动识别为 ID)
@batch_cmaps([item[0] for item in items])
def show_by_id(cmap_obj):
cmap.preview(cmap_obj)
show_by_id()
IDs: [1, 38, 39] Names: ['Accent', 'Afmhot', 'Autumn']
方式三: — 多种调用方式¶
支持名称列表、Collection、查询 kwargs、query_func 等多种调用风格。
In [7]:
Copied!
# 名称列表方式
@batch_cmaps(["Viridis", "Plasma", "Inferno"])
def show_names(cmap_obj):
cmap.preview(cmap_obj)
show_names()
# query_func 方式
@batch_cmaps(query_func=lambda: cmap.names(cmap_type="diverging", is_custom=False))
def show_diverging(cmap_obj):
cmap.preview(cmap_obj)
show_diverging()
# 名称列表方式
@batch_cmaps(["Viridis", "Plasma", "Inferno"])
def show_names(cmap_obj):
cmap.preview(cmap_obj)
show_names()
# query_func 方式
@batch_cmaps(query_func=lambda: cmap.names(cmap_type="diverging", is_custom=False))
def show_diverging(cmap_obj):
cmap.preview(cmap_obj)
show_diverging()
方式五:ColormapRenderer.render_grid()¶
如果只需要快速预览色带条(不需要自定义绘制),用 ColormapRenderer.render_grid() 更简洁。
In [8]:
Copied!
import matplotlib.pyplot as plt
from multicolor.render import ColormapRenderer
# 获取色带对象列表
items = cmap.list(colorblind_safe="any", is_custom=False, limit=6)
cmaps = [(name, cm) for _, name, cm in items]
fig, axes = ColormapRenderer.render_grid(cmaps, cols=3)
plt.show()
import matplotlib.pyplot as plt
from multicolor.render import ColormapRenderer
# 获取色带对象列表
items = cmap.list(colorblind_safe="any", is_custom=False, limit=6)
cmaps = [(name, cm) for _, name, cm in items]
fig, axes = ColormapRenderer.render_grid(cmaps, cols=3)
plt.show()
方式六:ColormapCollection 批量出图¶
将筛选后的色带批量导出为 PNG 文件。
In [9]:
Copied!
import os
# 筛选出色盲安全 + matplotlib 来源的色带
collection = cmap.collection(
is_custom=False, colorblind_safe="any", source="matplotlib"
)
print(f"Selected {len(collection)} colormaps: {collection.names}")
# 保存到 notebook 同目录下
outdir = os.path.join(os.getcwd(), "exported_cmaps")
collection.export_images(outdir, orientation="horizontal", size=(6, 0.8), dpi=150)
print(f"\nExported files:")
for f in sorted(os.listdir(outdir)):
print(f" {f}")
import os
# 筛选出色盲安全 + matplotlib 来源的色带
collection = cmap.collection(
is_custom=False, colorblind_safe="any", source="matplotlib"
)
print(f"Selected {len(collection)} colormaps: {collection.names}")
# 保存到 notebook 同目录下
outdir = os.path.join(os.getcwd(), "exported_cmaps")
collection.export_images(outdir, orientation="horizontal", size=(6, 0.8), dpi=150)
print(f"\nExported files:")
for f in sorted(os.listdir(outdir)):
print(f" {f}")
Selected 53 colormaps: ['Autumn', 'Berlin', 'Binary', 'Blues', 'Bone', 'BrBG', 'BuGn', 'BuPu', 'Cividis', 'Cool', 'Coolwarm', 'Copper', 'Cubehelix', 'Gist_earth', 'Gist_gray', 'Gist_yarg', 'GnBu', 'Gray', 'Greens', 'Greys', 'Inferno', 'Magma', 'Managua', 'Ocean', 'OrRd', 'Oranges', 'PRGn', 'PiYG', 'Plasma', 'PuBu', 'PuBuGn', 'PuOr', 'PuRd', 'Purples', 'RdBu', 'RdGy', 'RdPu', 'RdYlBu', 'RdYlGn', 'Reds', 'Seismic', 'Spectral', 'Spring', 'Summer', 'Turbo', 'Vanimo', 'Viridis', 'Winter', 'Wistia', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']
Exported files: Autumn.png Berlin.png Binary.png Blues.png Bone.png BrBG.png BuGn.png BuPu.png Cividis.png Cool.png Coolwarm.png Copper.png Cubehelix.png Gist_earth.png Gist_gray.png Gist_yarg.png GnBu.png Gray.png Greens.png Greys.png Inferno.png Magma.png Managua.png Ocean.png OrRd.png Oranges.png PRGn.png PiYG.png Plasma.png PuBu.png PuBuGn.png PuOr.png PuRd.png Purples.png RdBu.png RdGy.png RdPu.png RdYlBu.png RdYlGn.png Reds.png Seismic.png Spectral.png Spring.png Summer.png Turbo.png Vanimo.png Viridis.png Winter.png Wistia.png YlGn.png YlGnBu.png YlOrBr.png YlOrRd.png