Skip to main content
 首页 » 编程设计

python之python 中的热图之带颜色

2024年10月01日8kevingrace

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

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

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

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) 

由此,我获得了左侧 body 点击的热图、右侧 body 点击的热图以及左右 body 的图片。我希望它们都在同一张图片中,带有蓝色和红色热点。我附上了我得到的照片。

2个body picture(我在上面画了蓝点,但是我不需要这些点):

左右 body 的热图:

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

请您参考如下方法:

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

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 https://stackoverflow.com/q/15003353/1461210 
left_cb.solids.set_edgecolor("face") 
right_cb.solids.set_edgecolor("face") 
 
fig.tight_layout() 

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