首页 > 解决方案 > 如何在 matplotlib 中创建自定义发散颜色图?

问题描述

我想在 matplotlib 中创建一个类似于“RdBu”的颜色图。 传统的

我想让这个序列中的颜色图为浅蓝色->深蓝色->黑色(中心)->深红色->浅红色。像这样的东西。 所需的颜色图

所以它类似于“RdBu”,但白色变为黑色和深色与浅色互换。所以它只是反转“RdBu”颜色。我不知道该怎么做。

标签: pythonmatplotlibcolormap

解决方案


我最近只是尝试创建一个颜色图来满足我的要求。这是我尝试构建您需要的颜色图。我知道这并不完美。但它向您展示了如何开始。

import matplotlib
import matplotlib.cm as cm
from matplotlib.colors import Normalize
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

# create sample data set
# both will be: 0 - 1
x = np.random.rand(400)
y = np.random.rand(400)
# for realistic use
# set extreme values -900, +900 (approx.)
rval = 900
z = ((x+y)-1)*rval

# set up fig/ax for plotting
fig, ax = plt.subplots(figsize=(5, 5))

# option: set background color
ax.set_facecolor('silver')

# the colormap to create
low2hiColor = None

# create listedColormap
bottom = cm.get_cmap('Blues', 256)
top = cm.get_cmap('Reds_r', 256)
mycolormap = np.vstack((bottom(np.linspace(0.25, 1, 64)),
                        np.array([
                        [0.03137255, 0.08823529, 0.41960784, 1.],
                        [0.02137255, 0.04823529, 0.21960784, 1.],
                        [0.01137255, 0.02823529, 0.11960784, 1.],
                        [0.00037255, 0.00823529, 0.00960784, 1.],
                        #[0.00000255, 0.00000529, 0.00060784, 1.],
                        ])
                       ))
mycolormap = np.vstack((mycolormap,
                        np.array([
                        #[0.00060784, 0.00000529, 0.00000255, 1.],
                        [0.00960784, 0.00823529, 0.00037255, 1.],
                        [0.11960784, 0.02823529, 0.01137255, 1.],
                        [0.21960784, 0.04823529, 0.02137255, 1.],
                        [0.41960784, 0.08823529, 0.03137255, 1.],
                        ])
                       ))
mycolormap = np.vstack((mycolormap,
                        top(np.linspace(0, 0.75, 64)),
                       ))

low2hiColor = ListedColormap(mycolormap, name='low2hiColor')

# colorbar is created separately using pre-determined `cmap`
minz = -900 #min(z)
maxz = 900  #max(z)
norm_low2hiColor = matplotlib.colors.Normalize(minz, maxz)

# plot dataset as filled contour
norm1 = matplotlib.colors.Normalize(minz, maxz)
cntr1 = ax.tricontourf(x, y, z, levels=64, cmap=low2hiColor, norm=norm1)

gridlines = ax.grid(b=True)  # this plot grid

cbar= plt.colorbar( cntr1 ) 
plt.title("Light-Dark Blue Black Dark-Light Red")
plt.show()

示例图:

贝克尔


推荐阅读