python - 创建渐变色图 - matplotlib

标签 python matplotlib colors colormap

我正在尝试创建一个 colormap,它是从 dark red 到非常 light green/white 的渐变。我将在下面附上一个输出示例作为屏幕截图。

enter image description here

我试过以下代码:

from matplotlib import pyplot as plt
import matplotlib 
import numpy as np

plt.figure()
a=np.outer(np.arange(0,1,0.01),np.ones(100))
cdict2 = {'red':   [(0.0,  0.1, 0.2),
                   (0.3,  0.4, 0.5),
                   (0.5,  0.5, 0.5),
                   (1.0,  1.0, 1.0)],
         'green': [(0.0,  0.0, 0.0),
                  (0.5, 0.5, 0.5),
                  (0.75, 1.0, 1.0),
                  (1.0,  1.0, 1.0)],
         'blue':  [(0.0,  0.0, 0.0),
                  (0.0,  0.0, 0.0),
                  (1.0,  1.0, 1.0)]} 
my_cmap2 = matplotlib.colors.LinearSegmentedColormap('my_colormap2',cdict2,256)
plt.imshow(a,aspect='auto', cmap =my_cmap2)                   
plt.show()

但我无法复制附加的colormap。我也不确定是否有更有效的方法来实现这一点?

当前输出:我已经操纵这些值来尝试获取 gradient 来复制附加的 colormap。但是我无法得到 red-orange-yellow-green gradient correct

enter image description here

最佳答案

由于您是在尝试模拟现有的渐变而不是从任意颜色创建渐变,因此只需找到一个与测得的渐变值相匹配的公式即可。

首先获取梯度上每个点的平均像素 r、g、b 值。你需要先得到一个纯图像,你发布的那个有一个白色的边框,边缘有一些响铃;我使用图像编辑器来清理它。

获得测量值后,您可以使用 numpy.polyfit做曲线拟合。我疯狂地猜测 5 度就足以很好地拟合,从而产生一个包含 6 个系数的数组。在这里,您可以看到覆盖了拟合曲线的测量值图。我会说这是一场相当不错的比赛。

R,G,B measured values and curve fit

下面是使用这些曲线重新创建渐变的代码。

rp = [-1029.86559098,  2344.5778132 , -1033.38786418,  -487.3693808 ,
         298.50245209,   167.25393272]
gp = [  551.32444915, -1098.30287507,   320.71732031,   258.50778539,
         193.11772901,    30.32958789]
bp = [  222.95535971, -1693.48546233,  2455.80348727,  -726.44075478,
         -69.61151887,    67.591787  ]

def clamp(n):
    return min(255, max(0, n))

def gradient(x, rfactors, gfactors, bfactors):
    '''
    Return the r,g,b values along the predefined gradient for
    x in the range [0.0, 1.0].
    '''
    n = len(rfactors)
    r = clamp(int(sum(rfactors[i] * (x**(n-1-i)) for i in range(n))))
    g = clamp(int(sum(gfactors[i] * (x**(n-1-i)) for i in range(n))))
    b = clamp(int(sum(bfactors[i] * (x**(n-1-i)) for i in range(n))))
    return r, g, b

from PIL import Image
im = Image.new('RGB', (742, 30))
ld = im.load()
for x in range(742):
    fx = x / (742 - 1)
    for y in range(30):
        ld[x,y] = gradient(fx, rp, gp, bp)

new gradient

关于python - 创建渐变色图 - matplotlib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53754012/

相关文章:

python - 在 Python 中并行下载多个 S3 对象

python for 循环子图

随机生成美观的调色板的算法

python - Matplotlib:子图的高度相同

python - matplotlib 的视网膜显示模式是什么?

java - 在Java中更改png的非透明部分的颜色

android - 如何将#RGB 转换为#RRGGBB

python - 使用 Python 获取 MySQL 表中最常见的单词

python pandas date time 输出日期相同

python - 如何从QThread调用widget的方法