python - 使用 matplotlib.colors.Colormap 将标量值映射到 RGB 时出现奇怪的颜色图

标签 python matplotlib plot colors

我正在尝试从给定特定 matplot 库颜色映射的输入标量中获取 RGB 十六进制字符串。我使用 matplotlib.get_cmap() 获取 matplotlib.colors.Colormap 对象,并将一个范围为 (0, 1) 的标量传递给该 map 以获取 RGBA 值,然后绘制该颜色。但有时绘制的颜色与 imshow() 绘制的颜色不同。我在这里做傻事吗?

复制代码

import matplotlib.pyplot as plt
import numpy as np
plt.ioff()

cmap = 'RdBu_r'
cmap = plt.get_cmap(cmap)

f = plt.figure(figsize=(8, 4))
ax1 = f.add_subplot(121)
ax2 = f.add_subplot(122)
plot_arr = np.arange(100).reshape((10, 10)) / 99.
ax1.imshow(plot_arr, vmin=0., vmax=1., cmap=cmap, interpolation='nearest')

for i in range(10):
    for j in range(10):
        curr_rgb = cmap(plot_arr[i, j])[0:3]
        curr_rgb = tuple([int(x * 255) for x in curr_rgb])
        r, g, b = curr_rgb
        curr_cstr = '#{:0<2}{:0<2}{:0<2}'.format(hex(r)[2:], hex(g)[2:], hex(b)[2:])
        ax2.plot(j, i, 'o', mfc=curr_cstr, lw=0, mec='none', ms=20)

ax2.set_xlim([-0.5, 9.5])
ax2.set_ylim([9.5, -0.5])
plt.show()

实际结果
output image

预期结果 正如在代码中实现的那样,左图绘制为 imshow()。右图是根据输入标量用颜色图对象的颜色绘制的点。如果我的理解是正确的,同一个网格单元格的颜色应该是相同的。但在高值和低值时明显不同。

Matplotlib 版本
操作系统:windows 7 64位
Matplotlib 版本:2.0.2
Python版本:3.5.3
NumPy 的:1.13.0

最佳答案

虽然另一个答案很好地解释了问题代码失败的原因,但我想指出根本不需要将颜色转换为十六进制,您可以直接使用颜色图为图中的点着色。

您可以决定遍历这些点并直接将应用的颜色图值提供给绘图的 color 参数。 (中图)

或者您可以使用散点图并将 plot_arr 连同颜色图一起提供给它的 c 参数,如果需要,还可以进行归一化。 (右图)

enter image description here

import matplotlib.pyplot as plt
import numpy as np

cmapname = 'RdBu_r'
cmap = plt.get_cmap(cmapname)

plot_arr = np.arange(100).reshape((10, 10)) / 99.

fig, (ax1,ax2,ax3) = plt.subplots(ncols=3, figsize=(9, 3.5),subplot_kw={"aspect":"equal"})

ax1.set_title("image")
ax1.imshow(plot_arr, vmin=0., vmax=1., cmap=cmap, interpolation='nearest')

ax2.set_title("plot in loop")
for i in range(10):
    for j in range(10):
        ax2.plot(j, i, 'o', color=cmap(plot_arr[i, j]), lw=0, mec='none', ms=10)

ax2.set_ylim([9.5, -0.5])

ax3.set_title("scatter")
x = np.arange(0,10)
X,Y = np.meshgrid(x,x)
ax3.scatter(X,Y,c=plot_arr, s=100, vmin=0., vmax=1., cmap='RdBu_r', edgecolors="none")
ax3.set_ylim([9.5, -0.5])

plt.show()

关于python - 使用 matplotlib.colors.Colormap 将标量值映射到 RGB 时出现奇怪的颜色图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44936488/

相关文章:

python - Matplotlib 只是给出错误信息

python - 如何更改 matplotlib 中多个绘图的默认颜色?

python - 如何从 csv 文件中读取日期/时间字段并在 python 中相应地绘制图形

python - matplotlib 中的恒定颜色图。

python - 如何在 Pandas DataFrame 上编写条件数组操作

python - 创建绘图后更新它

python - Ruby 是否有相当于在 Python 中使用 matplotlib 和 basemap 的功能?

python - KNN - 在 python 中预测单个案例

javascript - Highcharts 的验证堆叠问题

python 和 Basemap 并从 View 中删除墨西哥/加拿大