[英]How to create a custom colormap with three colors?
I want to create a custom colormap with three colors, red-white-blue, using Matplotlib.我想使用 Matplotlib 创建一个自定义颜色图,其中包含三个 colors,红白蓝。
I know how to create a custom colormap with two colors.我知道如何使用两个 colors 创建自定义颜色图。 Here from red to blue:
这里从红到蓝:
import numpy as np
from matplotlib.colors import ListedColormap
N = 1024
vals = np.zeros((N, 4))
vals[:, 0] = np.linspace(1.0, 0.0, N) # red
vals[:, 2] = np.linspace(0.0, 1.0, N) # blue
vals[:, 3] = 1.0
my_cmap = ListedColormap(vals)
But how do I add the color white between red and blue?但是如何在红色和蓝色之间添加白色?
I used this adapted code from the matplotlib documentation我使用了 matplotlib 文档中的这个改编代码
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import ListedColormap
def plot_examples(colormaps):
"""
Helper function to plot data with associated colormap.
"""
np.random.seed(19680801)
data = np.random.randn(30, 30)
n = len(colormaps)
fig, axs = plt.subplots(1, n, figsize=(n * 2 + 2, 3),
constrained_layout=True, squeeze=False)
for [ax, cmap] in zip(axs.flat, colormaps):
psm = ax.pcolormesh(data, cmap=cmap, rasterized=True, vmin=-4, vmax=4)
fig.colorbar(psm, ax=ax)
plt.show()
# Red, Green, Blue
N = 256
vals = np.ones((N, 4))
# Red stays constant until middle of colormap all other channels increas
# to result in white
# from middle of colormap we decrease to 0, 0, 255 which is blue
vals[:, 0] = np.concatenate((np.linspace(1, 1, N//2), np.linspace(1, 0, N//2)), axis=None)
vals[:, 1] = np.concatenate((np.linspace(0, 1, N//2), np.linspace(1, 0, N//2)), axis=None)
vals[:, 2] = np.concatenate((np.linspace(0, 1, N//2), np.linspace(1, 1, N//2)), axis=None)
newcmp = ListedColormap(vals)
plot_examples([newcmp])
The output of this script looks similar to this此脚本的 output 看起来与此类似
You can just specify the colors in the ListedColormap
, like this:您可以在 ListedColormap 中指定
ListedColormap
,如下所示:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import ListedColormap
# make something to plot
x = np.linspace(0, 10, 400)
y = np.linspace(0, 10, 400)
xv, yv = np.meshgrid(x, y)
z = np.sin(xv*yv)
# make the color map:
cmp = ListedColormap(['red', 'white', 'blue'])
# do the plot
plt.pcolormesh(z, cmap=cmp)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.