Python 在 matplotlib 中反转颜色图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3279560/
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
Reverse colormap in matplotlib
提问by Mermoz
I would like to know how to simply reverse the color order of a given colormap in order to use it with plot_surface.
我想知道如何简单地反转给定颜色图的颜色顺序,以便将其与 plot_surface 一起使用。
采纳答案by ptomato
The standard colormaps also all have reversed versions. They have the same names with _rtacked on to the end. (Documentation here.)
标准颜色图也都有反向版本。它们具有相同的名称,_r并添加到末尾。(文档在这里。)
回答by Gilles
In matplotlib a color map isn't a list, but it contains the list of its colors as colormap.colors. And the module matplotlib.colorsprovides a function ListedColormap()to generate a color map from a list. So you can reverse any color map by doing
在 matplotlib 中,颜色映射不是列表,但它包含其颜色列表作为colormap.colors. 并且该模块matplotlib.colors提供了ListedColormap()从列表生成颜色图的功能。所以你可以通过做来反转任何颜色图
colormap_r = ListedColormap(colormap.colors[::-1])
回答by Mattijn
As a LinearSegmentedColormapsis based on a dictionary of red, green and blue, it's necessary to reverse each item:
由于 aLinearSegmentedColormaps是基于红、绿、蓝的字典,所以有必要对每一项进行反转:
import matplotlib.pyplot as plt
import matplotlib as mpl
def reverse_colourmap(cmap, name = 'my_cmap_r'):
"""
In:
cmap, name
Out:
my_cmap_r
Explanation:
t[0] goes from 0 to 1
row i: x y0 y1 -> t[0] t[1] t[2]
/
/
row i+1: x y0 y1 -> t[n] t[1] t[2]
so the inverse should do the same:
row i+1: x y1 y0 -> 1-t[0] t[2] t[1]
/
/
row i: x y1 y0 -> 1-t[n] t[2] t[1]
"""
reverse = []
k = []
for key in cmap._segmentdata:
k.append(key)
channel = cmap._segmentdata[key]
data = []
for t in channel:
data.append((1-t[0],t[2],t[1]))
reverse.append(sorted(data))
LinearL = dict(zip(k,reverse))
my_cmap_r = mpl.colors.LinearSegmentedColormap(name, LinearL)
return my_cmap_r
See that it works:
看看它是否有效:
my_cmap
<matplotlib.colors.LinearSegmentedColormap at 0xd5a0518>
my_cmap_r = reverse_colourmap(my_cmap)
fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = my_cmap, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = my_cmap_r, norm=norm, orientation='horizontal')
EDIT
编辑
I don't get the comment of user3445587. It works fine on the rainbow colormap:
我没有得到 user3445587 的评论。它在彩虹色图上工作正常:
cmap = mpl.cm.jet
cmap_r = reverse_colourmap(cmap)
fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = cmap, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = cmap_r, norm=norm, orientation='horizontal')
But it especially works nice for custom declared colormaps, as there is not a default _rfor custom declared colormaps. Following example taken from http://matplotlib.org/examples/pylab_examples/custom_cmap.html:
但它特别适用于自定义声明的颜色图,因为自定义声明的颜色图没有默认值_r。以下示例取自http://matplotlib.org/examples/pylab_examples/custom_cmap.html:
cdict1 = {'red': ((0.0, 0.0, 0.0),
(0.5, 0.0, 0.1),
(1.0, 1.0, 1.0)),
'green': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 1.0),
(0.5, 0.1, 0.0),
(1.0, 0.0, 0.0))
}
blue_red1 = mpl.colors.LinearSegmentedColormap('BlueRed1', cdict1)
blue_red1_r = reverse_colourmap(blue_red1)
fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = blue_red1, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = blue_red1_r, norm=norm, orientation='horizontal')
回答by overseas
There are two types of LinearSegmentedColormaps. In some, the _segmentdata is given explicitly, e.g., for jet:
有两种类型的 LinearSegmentedColormap。在某些情况下,_segmentdata 是明确给出的,例如,对于 jet:
>>> cm.jet._segmentdata
{'blue': ((0.0, 0.5, 0.5), (0.11, 1, 1), (0.34, 1, 1), (0.65, 0, 0), (1, 0, 0)), 'red': ((0.0, 0, 0), (0.35, 0, 0), (0.66, 1, 1), (0.89, 1, 1), (1, 0.5, 0.5)), 'green': ((0.0, 0, 0), (0.125, 0, 0), (0.375, 1, 1), (0.64, 1, 1), (0.91, 0, 0), (1, 0, 0))}
For rainbow, _segmentdata is given as follows:
对于rainbow,_segmentdata 给出如下:
>>> cm.rainbow._segmentdata
{'blue': <function <lambda> at 0x7fac32ac2b70>, 'red': <function <lambda> at 0x7fac32ac7840>, 'green': <function <lambda> at 0x7fac32ac2d08>}
We can find the functions in the source of matplotlib, where they are given as
我们可以在 matplotlib 的源代码中找到这些函数,它们被给出为
_rainbow_data = {
'red': gfunc[33], # 33: lambda x: np.abs(2 * x - 0.5),
'green': gfunc[13], # 13: lambda x: np.sin(x * np.pi),
'blue': gfunc[10], # 10: lambda x: np.cos(x * np.pi / 2)
}
Everything you want is already done in matplotlib, just call cm.revcmap, which reverses both types of segmentdata, so
你想要的一切都已经在matplotlib中完成了,只需调用cm.revcmap,它反转了两种类型的segmentdata,所以
cm.revcmap(cm.rainbow._segmentdata)
should do the job - you can simply create a new LinearSegmentData from that. In revcmap, the reversal of function based SegmentData is done with
应该完成这项工作 - 您可以简单地从中创建一个新的 LinearSegmentData 。在 revcmap 中,基于函数的 SegmentData 的反转是通过
def _reverser(f):
def freversed(x):
return f(1 - x)
return freversed
while the other lists are reversed as usual
而其他列表像往常一样颠倒
valnew = [(1.0 - x, y1, y0) for x, y0, y1 in reversed(val)]
So actually the whole thing you want, is
所以实际上你想要的整件事就是
def reverse_colourmap(cmap, name = 'my_cmap_r'):
return mpl.colors.LinearSegmentedColormap(name, cm.revcmap(cmap._segmentdata))
回答by Jm M
The solution is pretty straightforward. Suppose you want to use the "autumn" colormap scheme. The standard version:
解决方案非常简单。假设您要使用“秋季”颜色图方案。标准版:
cmap = matplotlib.cm.autumn
To reverse the colormap color spectrum, use get_cmap() function and append '_r' to the colormap title like this:
要反转颜色图色谱,请使用 get_cmap() 函数并将“_r”附加到颜色图标题,如下所示:
cmap_reversed = matplotlib.cm.get_cmap('autumn_r')
回答by astrofrog
There is no built-in way (yet) of reversing arbitrary colormaps, but one simple solution is to actually not modify the colorbar but to create an inverting Normalize object:
目前还没有反转任意颜色图的内置方法,但一个简单的解决方案是实际上不修改颜色条而是创建一个反转的 Normalize 对象:
from matplotlib.colors import Normalize
class InvertedNormalize(Normalize):
def __call__(self, *args, **kwargs):
return 1 - super(InvertedNormalize, self).__call__(*args, **kwargs)
You can then use this with plot_surfaceand other Matplotlib plotting functions by doing e.g.
然后,您可以plot_surface通过执行例如将其与其他 Matplotlib 绘图函数一起使用
inverted_norm = InvertedNormalize(vmin=10, vmax=100)
ax.plot_surface(..., cmap=<your colormap>, norm=inverted_norm)
This will work with any Matplotlib colormap.
这适用于任何 Matplotlib 颜色图。
回答by David Stansby
As of Matplotlib 2.0, there is a reversed()method for ListedColormapand LinearSegmentedColorMapobjects, so you can just do
从 Matplotlib 2.0 开始,有一个reversed()用于ListedColormap和LinearSegmentedColorMap对象的方法,所以你可以这样做
cmap_reversed = cmap.reversed()
cmap_reversed = cmap.reversed()
Hereis the documentation.
这是文档。


