首页 > 解决方案 > 生成从散点图的值推算的热图?

问题描述

我有一个具有不同强度的数据的熊猫数据框散点图(以冷色到暖色编码),我想将其转换为连续的分箱输出,类似于热图。

原始散点图

在阅读了几个问题后,我看到大多数人都在使用涉及转换为密度图或二维直方图的方法,例如下面的代码(仍在使用我的数据框sim):

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from scipy.ndimage.filters import gaussian_filter

def myplot(x, y, s, bins=1000):
    heatmap, xedges, yedges = np.histogram2d(x, y, bins=bins)
    heatmap = gaussian_filter(heatmap, sigma=s)

    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
    return heatmap.T, extent

fig, axs = plt.subplots(2, 2)

# Generate some test data

sigmas = [0, 16, 32, 64]

for ax, s in zip(axs.flatten(), sigmas):
    if s == 0:
        ax.scatter(sim[0], sim[1], s=10, lw=0, c=sim["Choice"],cmap='coolwarm', label='Choice')
        ax.set_title("Scatter plot")
    else:
        img, extent = myplot(sim[0], sim[1], s)
        ax.imshow(img, extent=extent, origin='lower', cmap=cm.jet)
        ax.set_title("Smoothing with  $\sigma$ = %d" % s)

plt.show()

尝试生成热图

或者:

import numpy as np
import matplotlib.pyplot as plt

plt.hist2d(sim[0],sim[1],weights=sim["Choice"],bins=100,cmap="coolwarm")

plt.show()

创建热图的其他尝试

我怎么能不进行计数/求和操作而选择不同的方式来估算图中每个单元格/区域的值?

在这种情况下,我想取附近点的平均值(如果附近没有点,则为 0),但是说我想要模式,或最近的邻居值,或图中位置的某些函数,其中包含点和每个点的值作为输入。我怎么能做这样的事情?

我的数据框中的几行示例数据sim

        0          1         Choice
 0  -4.809010   -3.207281   0.078947
 1  4.367746    -0.207146   0.421053
 2  3.764409    4.295580    0.026316
 3  -0.748293   -1.657736   0.263158
 4  -3.867472   3.846792    0.421053
 5  4.369304    0.823736    0.105263
 6  4.181189    -0.651535   0.131579
 7  -0.748293   -1.657736   0.500000
 8  -5.766971   -0.585494   0.131579
 9  2.498427    0.322623    0.210526
10  2.626870    4.064973    0.473684

标签: pythonmatplotlibdata-visualizationheatmapbinning

解决方案


推荐阅读