python中特定几何体的二维等值线图

时间:2013-11-11 20:02:52

标签: python numpy matplotlib

我想绘制特定几何体(多边形)的等高线图。我有角的坐标和这个多边形内的一些点,我想要插入到一个等值线图中的一维参数。我能够绘制参数的分布,但图像是一个正方形(因为我不知道如何指定我的几何)。 不用说我是Python初学者......

我目前使用以下代码;

import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate

r = np.array([[0, 0, 1.0000], [0, 1.0000, 0], [1.0000, 0, 0], [0, 0.7071, 0.7071],
[0, -0.7071, 0.7071],[0.7071, 0, 0.7071], [-0.7071, 0, 0.7071], [0.7071, 0.7071, 0], 
[-0.7071, 0.7071, 0], [0.8361,  0.3879, 0.3879], [-0.8361, 0.3879, 0.3879], 
[0.8361, -0.3879, 0.3879], [-0.8361, -0.3879, 0.3879], [0.3879, 0.8361, 0.3879],
[-0.3879, 0.8361, 0.3879], [0.3879, -0.8361, 0.3879], [-0.3879, -0.8361, 0.3879],
[0.3879, 0.3879, 0.8361], [-0.3879, 0.3879, 0.8361], [0.3879, -0.3879, 0.8361],
[-0.3879, -0.3879, 0.8361], [-1.0000, 0, 0], [-0.7071, -0.7071, 0], [0, -1.0000, 0],
[0.7071, -0.7071, 0]])

xx = r[:,0]
yy = r[:,1]
zz = r[:,2]

xxi, yyi = np.linspace(xx.min(), xx.max(), 100), np.linspace(yy.min(), yy.max(), 100)
xxi, yyi = np.meshgrid(xxi, yyi)

rbff = scipy.interpolate.Rbf(xx, yy, zz, function='linear')
zzi = rbff(xxi, yyi)
plt.imshow(zzi, vmin=zz.min(), vmax=zz.max(), origin='lower',
       extent=[xx.min(), xx.max(), yy.min(), yy.max()])
plt.scatter(xx, yy, c=zz)
plt.colorbar()
plt.show()   

2 个答案:

答案 0 :(得分:1)

这是作弊,但不过:你可以添加类似的东西

zzi = rbff(xxi, yyi)
zzi[zzi<0.1]=nan

并使用该值(此刻为0.1)。

答案 1 :(得分:0)

如果多边形是凸的,可以使用scipy.interpolate.griddata来获取蒙版区域:

import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate

r = np.array([[0, 0, 1.0000], [0, 1.0000, 0], [1.0000, 0, 0], [0, 0.7071, 0.7071],
[0, -0.7071, 0.7071],[0.7071, 0, 0.7071], [-0.7071, 0, 0.7071], [0.7071, 0.7071, 0], 
[-0.7071, 0.7071, 0], [0.8361,  0.3879, 0.3879], [-0.8361, 0.3879, 0.3879], 
[0.8361, -0.3879, 0.3879], [-0.8361, -0.3879, 0.3879], [0.3879, 0.8361, 0.3879],
[-0.3879, 0.8361, 0.3879], [0.3879, -0.8361, 0.3879], [-0.3879, -0.8361, 0.3879],
[0.3879, 0.3879, 0.8361], [-0.3879, 0.3879, 0.8361], [0.3879, -0.3879, 0.8361],
[-0.3879, -0.3879, 0.8361], [-1.0000, 0, 0], [-0.7071, -0.7071, 0], [0, -1.0000, 0],
[0.7071, -0.7071, 0]])

xx = r[:,0]
yy = r[:,1]
zz = r[:,2]

xxi, yyi = np.linspace(xx.min(), xx.max(), 100), np.linspace(yy.min(), yy.max(), 100)
xxi, yyi = np.meshgrid(xxi, yyi)

rbff = scipy.interpolate.Rbf(xx, yy, zz, function='linear')
zzi = rbff(xxi, yyi)
mask = np.isnan(scipy.interpolate.griddata(np.c_[xx, yy], zz, (xxi, yyi)))
zzi[mask] = np.nan
plt.imshow(zzi, vmin=zz.min(), vmax=zz.max(), origin='lower',
       extent=[xx.min(), xx.max(), yy.min(), yy.max()])
plt.scatter(xx, yy, c=zz)
plt.colorbar()
plt.show() 

输出:

enter image description here