从三个列表中绘制热图X,Y,强度 [英] Plotting a Heat Map X,Y,Intensity From Three Lists

查看:71
本文介绍了从三个列表中绘制热图X,Y,强度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我具有x,y,强度时,我不知道如何创建热图(或轮廓图).我有一个看起来像这样的文件:

I don't get how to create a heatmap (or contour plot) when I have x,y,intensity. I have a file which looks like this:

0,1,6
0,2,10
....

到目前为止:

with open('eye_.txt', 'r') as f:
        for line in f:
                for word in line.split():
                        l = word.strip().split(',')
                        x.append(l[0])
                        y.append(l[1])
                        z.append(l[2])

使用pcolormesh尝试过,但是它需要一个形状对象,我不确定如何将这些列表转换为numpy数组.

Tried using pcolormesh but it wants a shape object and I'm unsure how to convert these lists into a numpy array.

我尝试过:

i,j = np.meshgrid(x,y)
arr = np.array(z)
plt.pcolormesh(i,j,arr)
plt.show()

它告诉我:

IndexError: too many indices

有人可以阻止我用键盘b头吗?

Can someone stop me from bashing my head against a keyboard please?

推荐答案

好的,对此有一些步骤.

OK, there's a few steps to this.

首先,一种更简单的读取数据文件的方法是使用 numpy.genfromtxt .您可以使用delimiter参数将分隔符设置为逗号.

First, a much simpler way to read your data file is with numpy.genfromtxt. You can set the delimiter to be a comma with the delimiter argument.

接下来,我们要制作一个xy的2D网格,因此我们只需要将这些值中的唯一值存储到数组中以馈入numpy.meshgrid.

Next, we want to make a 2D mesh of x and y, so we need to just store the unique values from those to arrays to feed to numpy.meshgrid.

最后,我们可以使用这两个数组的长度来重塑我们的z数组.

Finally, we can use the length of those two arrays to reshape our z array.

(注意:此方法假定您有一个规则的网格,网格上的每个点都具有xyz).

(NOTE: This method assumes you have a regular grid, with an x, y and z for every point on the grid).

例如:

import matplotlib.pyplot as plt
import numpy as np

data = np.genfromtxt('eye_.txt',delimiter=',')

x=data[:,0]
y=data[:,1]
z=data[:,2]

## Equivalently, we could do that all in one line with:
# x,y,z = np.genfromtxt('eye_.txt', delimiter=',', usecols=(0,1,2))

x=np.unique(x)
y=np.unique(y)
X,Y = np.meshgrid(x,y)

Z=z.reshape(len(y),len(x))

plt.pcolormesh(X,Y,Z)

plt.show()

这篇关于从三个列表中绘制热图X,Y,强度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆