简体   繁体   English

Matplotlib:如何取消设置默认颜色图?

[英]Matplotlib: How to unset default colormap?

I am showing images with matplotlib and applying some colormaps to the images. 我正在显示带有matplotlib的图像,并将一些颜色图应用于图像。 I've figured you can set a default colormap by something like 我认为您可以通过以下方式设置默认颜色表:

plt.set_cmap('jet')

and then that colormap will be applied every time when using plt.imshow() 然后每次使用plt.imshow()时都会应用该颜色图

But how about undoing that? 但是如何消除呢? If I want to show the original images again without any colormap? 如果我想再次显示原始图像而没有任何颜色映射? I haven't found in the docs anything about that, neither by quick googling so any help would be appreciated. 我没有在文档中找到任何有关此的内容,也没有通过快速谷歌搜索找到任何帮助,因此不胜感激。

Thanks! 谢谢!

You can set the colormap using set_cmap as you are aware. 您可以使用set_cmap设置颜色图。 This changes the colormap for all subsequent figures plotted. 这将更改绘制的所有后续图形的颜色图。 If you want to undo the changes you have made, simply go back to the matplotlib default colormap, which in matplotlib 2 is viridis . 如果要撤消所做的更改,只需返回到matplotlib默认色图,在matplotlib 2中为viridis

However, there is also a cmap argument for imshow() which lets you change the colormap applied for an individual plot. 但是, imshow()也有一个cmap参数,可让您更改应用于单个图的颜色图。 This means you don't keep having to change the global colormap, however you would have to write this in every call to imshow() 这意味着不要将你不必改变全球的颜色表,但是你不得不在每次调用写这imshow()

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randn(25).reshape(5,5)

fig, (ax1, ax2) = plt.subplots(1,2)

ax1.imshow(data)
ax1.set_title("Matplotlib default cmap")

ax2.imshow(data, cmap='jet')
ax2.set_title("jet cmap")

plt.show()

Which gives: 这使:

在此处输入图片说明

The command plt.set_cmap("jet") sets the colormap in the rcParams to be the "jet" colormap. 命令plt.set_cmap("jet")将rcParams中的颜色图设置为"jet"颜色图。

In order to get back the default colormap, you can set the cmap to the default colormap from the rcParamsDefault dictionary. 为了获取默认颜色图,可以从rcParamsDefault字典中将cmap设置为默认颜色图。

import matplotlib.pyplot as plt
print(plt.rcParams["image.cmap"]) # prints viridis

plt.set_cmap("jet")
print(plt.rcParams["image.cmap"]) # prints jet

plt.set_cmap(plt.rcParamsDefault["image.cmap"])
print(plt.rcParams["image.cmap"]) # prints viridis

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

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