python - 如何在 matplotlib 中创建自定义发散颜色图?
问题描述
我想在 matplotlib 中创建一个类似于“RdBu”的颜色图。
我想让这个序列中的颜色图为浅蓝色->深蓝色->黑色(中心)->深红色->浅红色。像这样的东西。
所以它类似于“RdBu”,但白色变为黑色和深色与浅色互换。所以它只是反转“RdBu”颜色。我不知道该怎么做。
解决方案
我最近只是尝试创建一个颜色图来满足我的要求。这是我尝试构建您需要的颜色图。我知道这并不完美。但它向您展示了如何开始。
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()
示例图:
推荐阅读
- java - 我是否正确实施了 deltatime?
- parsing - 如何定义基于 ANTLR4 缩进块的语法?
- python - 如何使用Fastapi处理使用axios上传多个文件
- sql-server - 无法使用 invoke-sqlcmd 连接到 dockerized SQL Server
- jenkins - groovy.lang.MissingPropertyException:没有这样的属性:jenkinsproject 类:groovy.lang.Binding
- node.js - 从外部 3rd 方打字稿模块扩展类
- terraform - 如何应用单个 Terraform 模块?
- c - 将输入从文件重定向到 C 多处理程序时出错
- c# - 如何在面板的winforms中进行触摸式滚动?
- python - 反映 4d 对称数据