作者:LaravelChen | 来源:互联网 | 2023-02-02 12:46
我有一个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以适应数组.有了它我创建了我的数据的自定义直方图.
这是结果:
![在此输入图像描述](https://img.php1.cn/3cd4a/1e618/c5a/d5d40da532c3a782.png)
由于我必须为每个数组位置添加50,所以我的0索引不在正确的位置.但是numpy.histogram和numpy.histogram2d都不起作用.numpy.histogram给了我一个真正的直方图,而不是堆映射,而histogram2d不是正确的格式,我不知道如何将它带到正确的形状.
如何手动将我的索引设置到正确的位置或更改我的数组以获得正确的指示位置?
1> ImportanceOf..:
可以通过extent
关键字参数to 设置图像的数据范围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()
![在此输入图像描述](https://img.php1.cn/3cd4a/1eebe/cd5/bff2716168d1ed7b.webp)