如何通过样式表向matplotlib默认_color_full_map添加自定义命名颜色
结论
Matplotlib 原生 .mplstyle 样式表暂不支持直接配置自定义命名颜色,不过可以通过两种无需额外分发 JSON 文件的方案实现需求,调用逻辑也贴近原生 style.use 的使用习惯。
注意:不建议直接修改私有属性
_colors_full_map,该属性属于 Matplotlib 内部实现,版本迭代时可能发生变更,更推荐使用官方公开 APImpl.colors.register_color()注册自定义颜色。
方案1:封装样式加载函数,内置颜色映射
将自定义颜色映射直接写在样式加载函数中,用户仅需调用一次函数即可完成样式加载+颜色注册:
import matplotlib.pyplot as plt import matplotlib as mpl # 自定义颜色映射直接内置在代码中,无需额外外部文件 CUSTOM_COLORS = { "custom-name": "#ff5500", "custom-blue": "#2288dd", "custom-green": "#33aa77" } def load_custom_style(): # 加载原生自定义样式表 plt.style.use('custom-style-sheet') # 批量注册自定义颜色 for color_name, color_val in CUSTOM_COLORS.items(): mpl.colors.register_color(color_name, color_val) # 实际使用效果完全符合预期 if __name__ == "__main__": load_custom_style() fig, ax = plt.subplots() # 直接通过名称调用自定义颜色 artist, = ax.plot(x=[0, 1], y=[0, 1], c='custom-name') plt.show()
方案2:颜色配置嵌入样式表注释,单文件分发
如果希望所有配置都存放在单个 .mplstyle 文件中,可将自定义颜色写为固定格式的注释,加载时自动解析注册:
- 首先修改你的
custom-style-sheet.mplstyle文件,在末尾添加自定义颜色注释:
# 原有样式配置 axes.facecolor: #f8f8f8 lines.linewidth: 2 # 自定义颜色配置,格式为 #CUSTOM_COLOR: 颜色名 颜色值 #CUSTOM_COLOR: custom-name #ff5500 #CUSTOM_COLOR: custom-blue #2288dd #CUSTOM_COLOR: custom-green #33aa77
- 编写样式加载函数,自动解析注释注册颜色:
import re import matplotlib.pyplot as plt import matplotlib as mpl def load_custom_style(style_path: str): # 解析样式表中的自定义颜色注释 color_pattern = re.compile(r"^#CUSTOM_COLOR:\s*(\w+)\s*(#[0-9a-fA-F]{6,8})\s*$") with open(style_path, encoding="utf-8") as f: for line in f: match_res = color_pattern.match(line.strip()) if match_res: color_name, color_val = match_res.groups() mpl.colors.register_color(color_name, color_val) # 加载原生样式配置 plt.style.use(style_path) # 实际使用 if __name__ == "__main__": load_custom_style("custom-style-sheet.mplstyle") fig, ax = plt.subplots() artist, = ax.plot(x=[0, 1], y=[0, 1], c='custom-name') plt.show()
两种方案均无需额外分发JSON文件,第二种方案完全实现了单样式文件承载所有配置的需求,调用方式也和原生style.use基本一致。
内容的提问来源于stack exchange,提问作者Zach Roy
相关产品推荐
相关产品推荐

