【问题标题】:Generating Discrete Heatmap from 3D Data in Matplotlib在 Matplotlib 中从 3D 数据生成离散热图
【发布时间】:2017-08-06 21:29:41
【问题描述】:

所以我想做这样的事情:

Generating a heat map using 3D data in matplotlib

但我不希望我的颜色轴是连续的。


我的输入数据是这样的:

x = [0, 0, 0, ... , 20, 20, 20, ..., 39, 39, 39]
y = [0, 1, 2, ..., 0, 1, 2... , 37, 38, 39]
z = [0, 1, 0, ..., 1, 1, 0, ..., 1, 0 ,0]

换句话说,我的 z 值要么是 0,要么是 1,并且永远不会介于两者之间。

我试试:

 import numpy
 import matplotlib.pyplot as plt

 #===Load Data===#
 data = numpy.loadtxt("class_map.dat");

 #===Get Array Sizes===#
 max_x_size = int(numpy.sqrt(len(data[:,0])));
 max_y_size = int(numpy.sqrt(len(data[:,1])));

 #===Reshape Into Square Grid===#
 x = data[:,0]; xx = numpy.reshape(x, (max_x_size, max_x_size));
 y = data[:,1]; yy = numpy.reshape(y, (max_y_size, max_y_size));
 z = data[:,2]; zz = numpy.reshape(z, (max_x_size, max_y_size));

 #===Plot===#
 plt.subplot(111)
 plt.contourf(xx,yy,zz)
 plt.colorbar()
 plt.show();

但我得到的是:

看起来contourf 给了我一个连续函数。我希望它简单地显示 z 变量中已经存在的值,而不是为其拟合函数。我该怎么做?

编辑:另外,如果可能的话,我希望将离散值(0 或 1)设为灰度。

【问题讨论】:

    标签: python matplotlib heatmap


    【解决方案1】:

    您可以将levels 参数用于contour,例如levels=[0,0.5,1]

    import numpy as np
    import matplotlib.pyplot as plt
    
    #===Load Data===#
    x,y  = np.meshgrid(np.arange(20),np.arange(20) )
    data = np.random.randint(0,2, size=(20,20))
    
    #===Plot===#
    plt.subplot(111)
    plt.contourf(x,y,data, levels=[0,0.5,1])
    plt.colorbar()
    plt.show()
    

    另一种选择可能是使用imshow()

    import numpy as np
    import matplotlib.pyplot as plt
    
    #===Load Data===#
    x,y  = np.meshgrid(np.arange(20),np.arange(20) )
    data = np.random.randint(0,2, size=(20,20))
    
    #===Plot===#
    plt.subplot(111)
    plt.imshow(data, interpolation="None")
    plt.colorbar()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2017-04-12
      • 2014-05-17
      • 2011-01-23
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      • 2023-03-12
      相关资源
      最近更新 更多