在MatPlotLib中生成热图

2024-09-30 01:31:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试通过以下最上面的答案生成热图:Generate a heatmap in MatPlotLib using a scatter data set

在你们这些好心人的帮助下,我已经对我的数据进行了调整,这样我就可以相对轻松地(虽然代码不太漂亮)挖掘x和y坐标。在

坐标被很好地放入数组中,但是当我将这些数组插入热图代码时,我得到以下输出:

enter image description here

我使用的代码如下:

import csv
import string, numpy as np
import numpy as np
import numpy.random
import matplotlib.pyplot as plt
import pickle
import operator as oper
import re
from math import sqrt
import re # used here to remove non-numeric values



file = open('P2E2D_Long_Format.csv', 'rb')

reader1 = csv.reader(file, delimiter = '\t')
non_decimal = re.compile(r'[^\d.]+')

x = []
y = []

count = 0 

for row in reader1:
    #print row
    if 'SCL' in row[0] and count <= 5000:
        #print row[0]
        if len(row[2]) and len(row[3]) > 0: #ensures that x and y CoOr are not empty.
            if '   .' not in row[2] and 'SAMPLES' not in row[3]:
                #populates list with values in row 2 & 3            
                xCoOr = row[2]
                yCoOr = row[3]

                #this code removes the blank spaces before numbers
                x1 = non_decimal.sub('', xCoOr)
                y1 = non_decimal.sub('', yCoOr)
                print x1, 'XCoOr'
                print y1, 'YCoOr'


                #changes values from file, that are seen as string, to a float            
                x1 = float(x1)
                y1 = float(y1)
                #print x1            
                x = x + [x1]
                y = y + [y1]
                count = count + 1
                print count



myarrayx = np.asarray(x)
myarrayy = np.asarray(y)

myarrayx = myarrayx - 508
myarrayy = myarrayy - 384

myarrayx = myarrayx / 100
myarrayy = myarrayy / 100


heatmap, xedges, yedges = np.histogram2d(myarrayx, myarrayy, bins=50)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
plt.clf()
plt.imshow(heatmap, extent=extent)
plt.show()

file.close()   # <---IMPORTANT
#Long_Format.close()
#textFile.close()

第[0]行是试用ID,2行是x坐标,第[3]行是y坐标。在

当看到上面输出的图形时,它看起来好像y轴完全不存在。在

有人有什么想法吗?在

以下是我使用的一些数据:

^{pr2}$

编辑:我在“体形”窗口中手动操纵了x轴和y轴上的最小值和最大值,如下所示: enter image description here

可以看出,x轴的最大值是巨大的。我不知道为什么会这样。我怀疑这个值必须出现在我的数据中的xCoOr列中。在

然而,即使我调整了最大值和最小值,热图也是空白的。在

谢谢你在这方面的时间。在


Tags: andinimportascountnppltfile
1条回答
网友
1楼 · 发布于 2024-09-30 01:31:07

我的同事解决了这个问题。在

问题是长宽比。在

Artey是2000年第一次筛选出的大量数据。在

然后,我的同事编写了以下代码:

plt.imshow(heatmap, extent=extent, aspect='auto')

关键是他加的

aspect='auto'

这使x轴与y轴相匹配,从而使一切变得更加可见。在

校正输出:

enter image description here

感谢所有考虑过这个问题的人。在

相关问题 更多 >

    热门问题