首页 > 解决方案 > matplotlib 中未排序但规则间隔数据的轮廓图

问题描述

我有一个包含 x,y,z 数据点的数据文件,如下所示:

# X Y Z
1.0 1 0.1  
1.0 2 0.2  
1.0 3 0.3  
2.1 3 0.5  
2.1 2 0.2  
2.1 1 0.4  
...

我能够读取我想要的数据,并像这样绘制它:

import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt("data.dat",skiprows=1,usecols= (0,1,2))

X, Y = np.meshgrid(data[:,0], data[:,1])
Z = np.tile(data[:,2], (len(data[:,2]), 1))

fig=plt.figure()
plt.contourf(X,Y,Z,levels=50)
cbar = plt.colorbar()
plt.show()

然而,由此产生的轮廓是错误的。输入数据在网格(N x 值,M y 值)中规则间隔,但文件不是以排序方式创建的。在不知道 N 和 M 的确切值的情况下,如何确保数据被读入、正确排序。

标签: pythonnumpymatplotlib

解决方案


meshgrid不会以您使用它的方式产生您想要的东西。一种思考方式是meshgrid 创建数据(从n+m数据点到n*m + n*m数据点),但您不需要创建数据,您只需要对已有的数据进行排序和塑造。

您可以使用 numpy 对其进行排序,但对于这种情况,您想使用单列中的值对行进行排序,Pandas 更容易;在此处的示例中使用单行data.sort_values("Y")。这里的其他一切都只是对这条线的支持。

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# make some data and plot it... getting back to this is the goal
x = np.arange(4)
X, Y = np.meshgrid(x, x)
Z = X + Y
a = np.array([X, Y, Z])

fig=plt.figure()
plt.contourf(a[0], a[1], a[2])
cbar = plt.colorbar()

在此处输入图像描述

# now shuffle it and write to a file to mimic your data
np.random.shuffle(a.T)
b = a.reshape((3, -1))
with open("data.dat", 'w') as outfile:
    outfile.write("X Y Z\n")
    for i, j, k in b.T:
        outfile.write("%i %i %i\n" % (j, i, k))

# Here's where you start:
# now read in the data
data = pd.read_csv("data.dat", sep=" ")
# note that Y is out of order
print(data.T)  # print transposed to save space
#    0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15
# X  0  0  0  0  1  1  1  1  2  2   2   2   3   3   3   3
# Y  3  2  0  1  3  2  0  1  3  2   0   1   3   2   0   1
# Z  3  2  0  1  4  3  1  2  5  4   2   3   6   5   3   4

# sort the data
data2 = data.sort_values("Y")
#     2   6   10  14  3   7   11  15  1   5   9   13  0   4   8   12
# X   0   1   2   3   0   1   2   3   0   1   2   3   0   1   2   3
# Y   0   0   0   0   1   1   1   1   2   2   2   2   3   3   3   3
# Z   0   1   2   3   1   2   3   4   2   3   4   5   3   4   5   6

# Reshape and plot the data
c = data2.T.reshape((3, 4, 4))
fig=plt.figure()
plt.contourf(c[0], c[1], c[2])
cbar = plt.colorbar()

在此处输入图像描述


推荐阅读