【问题标题】:How to obtain RGB values for matplotlib color schemes?如何获取 matplotlib 配色方案的 RGB 值?
【发布时间】:2018-07-11 15:33:38
【问题描述】:

如何获取这些示例 cdict 值 (https://matplotlib.org/2.0.1/examples/pylab_examples/custom_cmap.html):

cdict = {'red':   ((0.0,  0.0, 0.0),
               (0.5,  1.0, 1.0),
               (1.0,  1.0, 1.0)),

     'green': ((0.0,  0.0, 0.0),
               (0.25, 0.0, 0.0),
               (0.75, 1.0, 1.0),
               (1.0,  1.0, 1.0)),

     'blue':  ((0.0,  0.0, 0.0),
               (0.5,  0.0, 0.0),
               (1.0,  1.0, 1.0))}

对于 matplotlib 中的 bwr 配色方案 (https://matplotlib.org/examples/color/colormaps_reference.html)?

【问题讨论】:

  • bwr 只是蓝白红。也许你想告诉你需要这些做什么,我怀疑这是xyproblem
  • 我想创建一个类似于 bwr 但中间白色部分范围更广的自定义配色方案。

标签: python matplotlib


【解决方案1】:

要回答这个问题,可以通过以下方式获得“bwr”颜色图的颜色

import matplotlib.cm
print(matplotlib.cm.datad["bwr"])

打印出来的

((0.0, 0.0, 1.0), (1.0, 1.0, 1.0), (1.0, 0.0, 0.0))

那就是["blue", "white", "red"]

不过,这对于实际应用可能不太有用。 要创建中间范围更广的白色颜色图,最好从颜色列表以及它们各自的值中创建颜色图。

为此,可以使用LinearSegmentedColormap.from_list方法。

from matplotlib.colors import LinearSegmentedColormap

colors = [(0, "blue"), (0.4, "white"), (0.6, "white"), (1, "red")]
cmap = LinearSegmentedColormap.from_list("bwwr", colors)

数字介于 0 和 1 之间,需要升序并表示相应颜色的“位置”。上面将创建一个颜色图,其从蓝色到白色的渐变介于 0 和 0.4 之间,然后是全白介于 0.4 和 0.6 之间,然后是从白色到红色的渐变,介于 0.6 和 1 之间。

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

colors = [(0, "blue"), (0.4, "white"), (0.6, "white"), (1, "red")]
cmap = LinearSegmentedColormap.from_list("bwwr", colors)

a = np.arange(0,100).reshape(10,10)

fig, (ax,ax2) = plt.subplots(ncols=2, figsize=(7,3))
im = ax.imshow(a, cmap="bwr")
fig.colorbar(im, ax=ax)
im2 = ax2.imshow(a, cmap=cmap)
fig.colorbar(im2, ax=ax2)

ax.set_title("bwr")
ax2.set_title("bwwr")
plt.show()

【讨论】:

  • 一个简单而优雅的方法!谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-09-16
  • 1970-01-01
  • 2019-09-25
  • 2021-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-07
相关资源
最近更新 更多