Python 如何在 Matplotlib 中设置默认颜色图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33185037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:58:26  来源:igfitidea点击:

How to set default colormap in Matplotlib

pythonmatplotlibcolor-mapping

提问by Jarno

Especially when working with grayscale images it is tedious to set the color map for every imshowcommand as imshow(i, cmap='gray'). How can I set the default color map matplotlib uses to grayscale or any other colormap?

特别是在处理灰度图像时,将每个imshow命令的颜色映射设置为imshow(i, cmap='gray'). 如何将 matplotlib 使用的默认颜色图设置为灰度或任何其他颜色图?

采纳答案by Jarno

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 matplotlibprior to 2.0 you have to use the rcParams dict. This still works in newer versions.

对于matplotlib2.0 之前的版本,您必须使用 rcParams dict。这仍然适用于较新的版本。

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. Replace the value gray with any other valid colormap according to your needs. The config file should be at ~/.config/matplotlib/matplotlibrc, but you can find out the exact location with

要永久更改默认颜色图,请编辑 matplotlibrc 配置文件并添加行image.cmap: gray. 根据您的需要,将灰色值替换为任何其他有效的颜色图。配置文件应该在 ~/.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.htmland 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

回答by Shital Shah

You can do either,

你可以这样做,

plt.set_cmap('jet')

or

或者

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

However note that if you are passing value for colorparameter in any of the APIs then this default will be ignored. In that case you should do something like this:

但是请注意,如果您color在任何 API 中为参数传递值,则此默认值将被忽略。在这种情况下,您应该执行以下操作:

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