Pyplot 1D热图问题

时间:2017-06-01 18:23:50

标签: python numpy matplotlib heatmap

我有一个完整的CSV文件,包含整数(正数和负数)并希望创建1D热图(或热棒,如果存在的话)。

到目前为止,这是我的代码:

import matplotlib as mat
import matplotlib.pyplot as plot
import numpy as np

import csv

a=([0,0])

a = np.resize(a,(1,96)) #the are 96 numbers from -56 to 40

with open('Start_0.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter = ';')
     k = np.array(list(reader)) #read every row in the CSV
     k = k.reshape((-1,7)) #every row has 7 data cells
     for row in k:

    i = int(row[4])                  #i only need the fourth cell
    if (i < 45)&(i > -50):           #if the number is between 45 and -50...
        a[0][i+50] = a[0][i+50] + 1  #increase the corresponding position by 1
print (a)

norm = mat.colors.Normalize(vmin=0, vmax=1)
plot.imshow(a, aspect = "auto", cmap="viridis", interpolation = "nearest")
plot.show()

我的数据是从高负数到高正数的数字,但只有-50到46之间的数字很有意思。这就是为什么我为我选择的每个数字添加50以适应数组。有了它,我创建了我的数据的自定义直方图。

结果如下: enter image description here

由于我必须为每个数组位置添加50,所以我的0索引不在正确的位置。但是numpy.histogram和numpy.histogram2d都不起作用。 numpy.histogram给了我一个真正的直方图,而不是堆映射,而histogram2d不是正确的格式,我不知道如何将它带到正确的形状。

如何手动将我的指数设置到正确的位置或更改我的数组以获得正确的指示位置?

1 个答案:

答案 0 :(得分:6)

可以通过extent关键字参数设置图像的数据范围imshow。这会使用元组(left, right, bottom, top)设置范围。 使用直方图的最小和最大bin边缘可以将数据移动到其原始值。

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
plt.rcParams["figure.figsize"] = 5,2

pos = np.arange(-56,40) #there are 96 numbers from -56 to 39
print len(pos), pos.min(), pos.max()
p = np.random.rand(len(pos))
p= p/np.sum(p)

a= np.random.choice(pos, size=4000, p=p) 
# now a contains 4000 numbers between -56 and 39

bins=np.arange(-56,41) #there are 96 bins, hence 97 edges from -56 to 40
hist, edges = np.histogram(a, bins)
hist=hist[np.newaxis,:]

extent=[bins.min(), bins.max(),0,1]
plt.imshow(hist, aspect = "auto", cmap="viridis", extent=extent)
plt.gca().set_yticks([])
plt.show()

enter image description here