如何在matplotlib中提取颜色图的子集作为新的颜色图? [英] how to extract a subset of a colormap as a new colormap in matplotlib?

查看:199
本文介绍了如何在matplotlib中提取颜色图的子集作为新的颜色图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用matplotlib中的颜色图,例如CMRmap.但是我不想在开头使用黑色"颜色,而在结尾使用白色"颜色.我有兴趣使用中间的颜色来绘制数据.我认为ppl经常使用它,但是我正在Internet上搜索,无法找到任何简单的解决方案.如果有人提出任何解决方案,我将不胜感激.

I would like to use a colormap from matplotlib e.g. CMRmap. But I don't want to use the "black" color at the beginning and the "white" color at the end. I'm interested to plot my data using the in-between colors. I think ppl use it quite often but I was searching over internet and could not manage to find any simple solution. I'll appreciate if someone suggest any solution.

推荐答案

静态方法

The staticmethod colors.LinearSegmentedColormap.from_list can be used to create new LinearSegmentedColormaps. Below, I sample the original colormap at 100 points between 0.2 and 0.8:

cmap(np.linspace(0.2, 0.8, 100))

并使用这些颜色生成新的颜色图:

and use these colors to generate a new colormap:

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import numpy as np

def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100):
    new_cmap = colors.LinearSegmentedColormap.from_list(
        'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval),
        cmap(np.linspace(minval, maxval, n)))
    return new_cmap

arr = np.linspace(0, 50, 100).reshape((10, 10))
fig, ax = plt.subplots(ncols=2)

cmap = plt.get_cmap('jet')
new_cmap = truncate_colormap(cmap, 0.2, 0.8)
ax[0].imshow(arr, interpolation='nearest', cmap=cmap)
ax[1].imshow(arr, interpolation='nearest', cmap=new_cmap)
plt.show()

左侧的图使用原始颜色图(在此示例中为jet)显示图像.右图使用new_cmap显示相同的图像.

The plot on the left shows the image using the original colormap (in this example, jet). The plot on the right shows the same image using new_cmap.

这篇关于如何在matplotlib中提取颜色图的子集作为新的颜色图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆