python 中的热图 - 带颜色

Aru*_*ion 3 python matplotlib heatmap

我尝试制作一个程序,根据参与者的点击绘制热图。有两个身体,情绪有增有减。

我想用蓝色显示左侧身体的点击强度(蓝色更强烈=点击次数更多),用红色显示右侧身体的点击强度。

问题是我需要在一个主体中显示它,并且还需要在背景图像上看到热图。

x=blue[:,1]
y=blue[:,2]
ax = plt.gca()

heatmap, xedges, yedges = np.histogram2d(x, y, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
plt.imshow(heatmap.T, extent=extent, origin='lower')
ax = plt.gca()
ax.invert_yaxis()

plt.show()

x1=red[:,1]
y1=red[:,2]
ax = plt.gca()

heatmap, xedges, yedges = np.histogram2d(x1, y1, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

plt.clf()
plt.imshow(heatmap.T, extent=extent, origin='lower')
ax = plt.gca()
ax.invert_yaxis()

plt.show()
plt.imshow(image)

imageFile = cbook.get_sample_data('C:\\Users\\Admin\\Desktop\\pythonpca\\result.png')
image = plt.imread(imageFile)
plt.plot(all_samples[0:240,0],all_samples[0:240,1], 'o', markersize=3, color='blue', alpha=0.5, label='increase')
plt.imshow(image)
Run Code Online (Sandbox Code Playgroud)

通过这个,我得到了左侧身体点击的热图、右侧身体点击的热图以及左侧和右侧身体的图片。我希望它们都在同一张图片中,带有蓝色和红色热点。我附上我得到的图片。

2张尸体图片(我在上面画了蓝点,但我不需要这些点):

2 人体图片(我在上面绘制了蓝色点,但我不需要这些点

左右身体的热图:

左右身体的热图

如果我应该添加更多信息,请告诉我。

ali*_*i_m 5

您可以使用两种不同的颜色来表示左侧和右侧的点击,并使用不透明度(Alpha 通道)来表示给定区域内的点击密度。一种方法是创建一个LinearSegmentedColormap在 alpha 通道中变化的自定义:

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

# Some fake data
nbins = (50, 50)
ranges = ((-2, 2), (-2, 2))
lx, ly = np.random.randn(2, 10000) * 0.5 + 1
rx, ry = np.random.randn(2, 10000) * 0.75 - 1

# Compute 2D histograms
left_density = np.histogram2d(lx, ly, bins=nbins, range=ranges, normed=True)[0]
right_density = np.histogram2d(rx, ry, bins=nbins, range=ranges, normed=True)[0]

# Make some custom colormaps that vary in the alpha channel.
trans2blue = colors.LinearSegmentedColormap.from_list(
    name='Trans2Blue', colors=[(0., 0., 1., 0.), (0., 0., 1., 1.)])
trans2red = colors.LinearSegmentedColormap.from_list(
    name='Trans2Red', colors=[(1., 0., 0., 0.), (1., 0., 0., 1.)])

# `imshow` the histograms using the custom colormaps.
fig, ax = plt.subplots(1, 1)
left_im = ax.imshow(left_density, cmap=trans2blue)
right_im = ax.imshow(right_density, cmap=trans2red)

right_cb = fig.colorbar(right_im)
right_cb.set_label('Right click density')
left_cb = fig.colorbar(left_im)
left_cb.set_label('Left click density')

# Workaround for /sf/ask/1050234741/
left_cb.solids.set_edgecolor("face")
right_cb.solids.set_edgecolor("face")

fig.tight_layout()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

实现相同效果的另一种方法是构造两个(rows, cols, 4)RGBA 像素值数组,其中 alpha 通道包含密度值,RGB 包含所需颜色,然后将imshow它们叠加在一起。不过,使用自定义颜色图有一些优点 - 颜色图范围会自动缩放,并且添加颜色条相当容易。