Matplotlib pcolormesh,分离数据颜色和颜色亮度信息

2024-09-29 17:16:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用matplotlib在网格上绘制数据,目前正在尝试pcolormesh。 数据被组织在两个numpy数组中,数据本身和colorInformation数组。在

下面的代码绘制了数据数组(1是红色的,0是蓝色的),但是我还有一个colorInformation数组,它应该根据每个单元格的值来改变其亮度,同时保持颜色。在

例如,数据中的行[1,0,0,1]应将亮度值[0.1,0.12,0.02,0.01]应用于绘图,这样该行将可视化为[红色和亮度0.1,蓝色和亮度0.12,蓝色和亮度0.02,红色和亮度0.01]

如何做到这一点?在

import numpy as np
import matplotlib.pyplot as plt

data = np.array([[1, 0, 0, 1], 
                 [0, 0, 1, 1], 
                 [0, 0, 0, 1]])
colorInformation = np.array([[0.1, 0.12, 0.02, 0.01], 
                             [0.12, 0.15, 0.18, 0.2], 
                             [0.3, 0.34, 0.41, 0.32]])

fig, ax = plt.subplots()
heatmap = ax.pcolormesh(data)
plt.show()

Tags: 数据importnumpydatamatplotlibasnp绘制
1条回答
网友
1楼 · 发布于 2024-09-29 17:16:15

我建议你自己定制颜色图来解决这个问题

from matplotlib.colors import LinearSegmentedColormap
data = np.array([[1, 0, 0, 1], 
                 [0, 0, 1, 1], 
                 [0, 0, 0, 1]])
colorInformation = np.array([[0.1, 0.12, 0.02, 0.01], 
                             [0.12, 0.15, 0.18, 0.2], 
                             [0.3, 0.34, 0.41, 0.32]])
alpha_up=abs(((data*2-1)*colorInformation).max())
alpha_low=abs(((data*2-1)*colorInformation).min())
mid=alpha_low/(alpha_up+alpha_low)
cdict1 = {'red':   ((0.0, 1.0, 1.0),
                   (mid, 1.0, 0.0),
                   (1.0, 0.0, 0.0)),

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

         'blue':  ((0.0, 0.0, 0.0),
                   (mid, 0.0, 1.0),
                   (1.0, 1.0, 1.0)),

         'alpha':  ((0.0, alpha_low, alpha_low),
                   (mid, 0.0, 0.0),
                   (1.0, alpha_up, alpha_up))
        }
red_blue = LinearSegmentedColormap('red_blue', cdict1)
fig, ax = plt.subplots()
heatmap = ax.pcolormesh((data*2-1)*colorInformation, cmap=red_blue)

enter image description here

或者你可以只改变红色和蓝色而不用阿尔法通道。在

相关问题 更多 >

    热门问题