显示带有 alpha 值的“热图”图像 - Matplotlib / Python

问题描述 投票:0回答:2

我正在尝试绘制一些数据来分析它们。

我的数据定义如下:

class Data(object):
    def __init__(self, rows=200, cols=300):
        """
        The Data constructor
        """
        # The data grid
        self.cols = cols
        self.rows = rows
        # The 2D data structure
        self.data = numpy.zeros((rows, cols), float)

一开始我有这样的方法:

  def generate_data_heat_map(data, x_axis_label, y_axis_label, plot_title, file_path):
    plt.figure()
    plt.title(plot_title)
    fig = plt.imshow(data.data, extent=[0, data.cols, data.rows, 0])
    plt.xlabel(x_axis_label)
    plt.ylabel(y_axis_label)
    plt.colorbar(fig)
    plt.savefig(file_path + '.png')
    plt.close()

这给了我一些热图图像(第二张图),因为我传递给它一个 MxN [亮度(灰度,仅限浮点数组)]。并且不知道为什么这不会生成灰度图像,但到目前为止我并不担心它,因为这就是我想要的结果。

经过更多计算,我用这种方法来可视化我的数据,使用 data_property 作为 RGB 和 data_uncertaity 作为 alpha:

def generate_data_uncertainty_heat_map(data_property, data_uncertainty, x_axis_label, y_axis_label, plot_title, file_path):
    plt.figure()
    uncertainty = numpy.zeros((data_property.rows, data_property.cols, 4))
    uncertainty[..., :3] = data_property.data[..., numpy.newaxis]
    uncertainty[..., 3] = data_uncertainty.data
    plt.title(plot_title)
    fig = plt.imshow(uncertainty.data, extent=[0, data_property.cols, data_property.rows, 0])
    plt.xlabel(x_axis_label)
    plt.ylabel(y_axis_label)
    plt.colorbar(fig)
    plt.savefig(file_path + '.png')
    plt.close()

但是,当然,这给了我一个带有 alpha 值的灰度图像,因为我对 R、G 和 B 重复相同的值。但我真正想要的是带有一些 alpha 值的第一个方法结果(彩色)计算为数据的不确定性。

enter image description here

我注意到我的颜色条也与我的数据无关(它是 RGB 格式,我不能用它来分析我的数据)

我不知道如何实现我想要的结果,即有一个“热图”图,其中合并了用我的 uncertainty_data 定义的 alpha 值和代表这种不确定性的颜色条。就像合并上面的两张图片一样:

这是我的颜色: Figure 2

这是我的阿尔法: enter image description here

通过@BlazBratanic 提供的转换,我想我可以看到一点颜色(不确定),但它远远超出了我的预期。

enter image description here

我所有的值都在 0.0 到 1.0 之间。

提前谢谢您。

python matplotlib rgba colorbar imshow
2个回答
1
投票

使用 Matplotlib cm 模块 将灰度映射到颜色值。如果我没记错的话“jet”是默认的颜色图。所以你会做类似的事情:

uncertainty = plt.cm.jet(data_property.data)
uncertainty[..., 3] = data_uncertainty.data

0
投票

如果我正确理解问题,并且使用我当前版本的 matplotlib (3.7.1),我可以只使用 alpha 关键字,所以类似

plt.imshow(data_array, ... ,alpha = alpha_array)

MWE 会是

import numpy
import matplotlib.pyplot as plt

mat = numpy.zeros((150,150))
mat[:,3] = 1
mat[:,45] = 1 #two vertical lines

counts = numpy.tile(numpy.array(list(range(1,151))).reshape(-1,1),[1,150])
counts = counts/numpy.max(counts) # alpha that increases linearly

plt.imshow(mat, cmap = 'binary', alpha = counts)
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.