2017-03-15 128 views
1

所以我希望做这样的事情:从3D数据生成离散热图中Matplotlib

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(); 

但我得到的是:

Result

看起来contourf是给我一个连续函数。我希望它只显示已经存在于z变量中的值,而不是为其添加函数。我怎样才能做到这一点?

编辑:另外,如果可能的话,我想在灰度上有离散值(0或1)。

回答

0

您可以使用contourlevels参数,例如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() 

enter image description here

另一个选项可以是使用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() 

enter image description here