【问题标题】:How can one create a heatmap from a 2D scatterplot data in Python?如何从 Python 中的 2D 散点图数据创建热图?
【发布时间】:2018-07-06 10:26:06
【问题描述】:

如何从 Python 中的 2D 散点图数据创建热图,散点图中的每个 (x,y) 点都有一个与之关联的 z 值? z 值将是用于为热图着色的值。


例如,在 R 中,我可以使用:

# This example is from http://knowledge-forlife.com/r-creating-heatmap-scatterplot-data/
#I'm just setting the seed so you can see the same example on your computer
set.seed(1)

#Our X data
x <- runif(150)

#Our Y data
y <- runif(150)

#Our Z data
z <- c(rnorm(mean=1,100),rnorm(mean=20,50))

#Store the length of our data
N <- length(x)

# View the scatterplot
plot(x, y)

#Here is the interpolation to give the heatmap effect. 
#Use xo and yo to set the output grid you want to use.
#xo and yo are used to change the resolution of the interpolation
#Here, I have included a somewhat standard protocol for these parameters
s <- interp(x,y,z,xo=seq(min(x),max(x),length=N),
            yo=seq(min(x),max(x),length=N),duplicate="mean")

#Here's where the fun happens
#Note you can add your typical plotting paramaters here, such as xlab or ylab
image.plot(s,xlim=c(0,1),ylim=c(0,1),zlim=c(-2,25))

散点图(此散点图中的每个 (x,y) 点都有一个与之关联的 z 值;z 值在散点图中不可见):

对应的热图(颜色代表z值):

请注意,此问题与 Generate a heatmap in MatPlotLib using a scatter data set 不同,其中热图中的颜色表示 (x,y) 点的密度。

【问题讨论】:

    标签: python heatmap


    【解决方案1】:

    以下是将您的代码翻译成python,使用numpy 进行向量运算,使用matplotlib 进行绘图:

    import numpy as np
    from matplotlib import pyplot
    
    x = np.random.uniform(size=150)
    y = np.random.uniform(size=150)
    z = np.concatenate([np.random.randn(100)+1, np.random.randn(50)+20])
    
    pyplot.plot(x, y, 'ok')
    pyplot.tricontourf(x, y, z)
    pyplot.show()
    

    这里的一个区别是我没有使用插值将 x 和 y 放在网格上,而是使用了matplotlib 的tricontourf,它使用了三角形镶嵌。如果你需要将数据放到一个矩形网格上,你可以使用scipy.interpolate.griddata,它与R中的interp函数非常相似。然后,为了绘制一个规则网格,你可以使用pyplot.pcolormesh。

    【讨论】:

      【解决方案2】:

      我接受了 Gerges Dib 的建议。这是代码,从 3D 高斯分布中采样 (x,y,z) 点:

      import numpy as np
      import scipy.interpolate
      from scipy.stats import multivariate_normal
      import matplotlib.pyplot as plt
      import seaborn as sns
      sns.set()
      
      # Sample from 3D Gaussian distribution
      np.random.seed(0)
      number_of_samples = 20
      x = np.random.rand(number_of_samples)
      y = np.random.rand(number_of_samples)
      xy = np.column_stack([x.flat, y.flat]) # Create a (N, 2) array of (x, y) pairs.
      mu = np.array([0.0, 0.0])
      sigma = np.array([.95, 2.5])
      covariance = np.diag(sigma**2)
      z = multivariate_normal.pdf(xy, mean=mu, cov=covariance)
      
      plt.scatter(x, y)
      plt.savefig('scatterplot.png', dpi=300)
      
      plt.tricontourf(x, y, z)
      plt.savefig('tricontourf.png', dpi=300)
      
      # Interpolate and generate heatmap:
      grid_x, grid_y = np.mgrid[x.min():x.max():1000j, y.min():y.max():1000j]
      for method in ['nearest','linear','cubic'] :
          plt.figure()
          grid_z = scipy.interpolate.griddata(xy,z,(grid_x, grid_y), method=method)
          # [pcolormesh with missing values?](https://stackoverflow.com/a/31687006/395857)
          import numpy.ma as ma
          plt.pcolormesh(grid_x, grid_y, ma.masked_invalid(grid_z), cmap='RdBu', vmin=np.nanmin(grid_z), vmax=np.nanmax(grid_z))
          plt.title('{0} interpolation'.format(method))
          plt.colorbar()
          plt.savefig('heatmap_interpolation_{0}.png'.format(method), dpi=300)
          plt.clf()
          plt.close()
      

      散点图.png:

      tricontourf.png:

      heatmap_interpolation_nearest.png

      heatmap_interpolation_linear.png:

      heatmap_interpolation_cubic.png:

      【讨论】:

        猜你喜欢
        • 2018-12-17
        • 1970-01-01
        • 2021-12-25
        • 2013-02-13
        • 2012-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多