简体   繁体   English

如何在Matplotlib中设置默认色彩映射

[英]How to set default colormap in Matplotlib

Especially when working with grayscale images it is tedious to set the color map for every imshow command as imshow(i, cmap='gray') . 特别是在处理灰度图像时,将每个imshow命令的颜色映射设置为imshow(i, cmap='gray')是很繁琐的。 How can I set the default color map matplotlib uses to grayscale or any other colormap? 如何设置matplotlib用于灰度或任何其他色彩映射的默认颜色映射?

To change the default colormap only for the current interactive session or one script use 仅为当前交互式会话或一个脚本使用更改默认色彩映射

import matplotlib as mpl
mpl.rc('image', cmap='gray')

For versions of matplotlib prior to 2.0 you have to use the rcParams dict. 对于2.0之前的matplotlib版本,您必须使用rcParams dict。 This still works in newer versions. 这仍然适用于较新的版本。

import matplotlib.pyplot as plt
plt.rcParams['image.cmap'] = 'gray'

To change the default colormap permanently edit the matplotlibrc configuration file and add the line image.cmap: gray . 要更改默认的image.cmap: gray映射,请永久编辑matplotlibrc配置文件并添加line image.cmap: gray Replace the value gray with any other valid colormap according to your needs. 根据需要将值替换为任何其他有效的colormap。 The config file should be at ~/.config/matplotlib/matplotlibrc , but you can find out the exact location with 配置文件应该在~/.config/matplotlib/matplotlibrc ,但你可以找到确切的位置

mpl.matplotlib_fname()

This is especially useful if you have multiple matplotlib versions in different virtual environments. 如果您在不同的虚拟环境中有多个matplotlib版本,这将特别有用。

See also http://txt.arboreus.com/2014/10/21/how-to-set-default-colormap-in-matplotlib.html and for general configuration of Matplotlib http://matplotlib.org/users/customizing.html 另见http://txt.arboreus.com/2014/10/21/how-to-set-default-colormap-in-matplotlib.html以及Matplotlib的一般配置http://matplotlib.org/users/customizing html的

You can do either, 你可以做到,

plt.set_cmap('jet')

or 要么

plt.rcParams['image.cmap']='jet'

However note that if you are passing value for color parameter in any of the APIs then this default will be ignored. 但请注意,如果要在任何API中传递color参数的值,则将忽略此默认值。 In that case you should do something like this: 在这种情况下,你应该做这样的事情:

color = plt.cm.hsv(r) # r is 0 to 1 inclusive
line = matplotlib.lines.Line2D(xdata, ydata, color=color)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM