Plotting Isolines/contours in matplotlib from (x, y, z) data set

蹲街弑〆低调 提交于 2019-12-17 07:54:27

问题


Hi I'm new to programming and I'm trying to do something that's probably really obvious but for the life of me I can't figure it out. I have a series of x, y, z data (in my case, corresponding to distance, depth, and pH). I would like to plot isolines of the z data (pH) on an xy (distance, depth) grid using matplotlib. Is there any way to do this? Thanks.


回答1:


The solution will depend on how the data is organized.

Data on regular grid

If the x and y data already define a grid, they can be easily reshaped to a quadrilateral grid. E.g.

#x  y  z
 4  1  3
 6  1  8
 8  1 -9
 4  2 10
 6  2 -1
 8  2 -8
 4  3  8
 6  3 -9
 8  3  0
 4  4 -1
 6  4 -8
 8  4  8 

can plotted as a contour using

import matplotlib.pyplot as plt
import numpy as np
x,y,z = np.loadtxt("data.txt", unpack=True)
plt.contour(x.reshape(4,3), y.reshape(4,3), z.reshape(4,3))

Arbitrary data

(a) In case the data is not living on a quadrilateral grid, one can interpolate the data on a grid. One method to do so is provided by matplotlib itself, using matplotlib.mlab.griddata.

import matplotlib.mlab
xi = np.linspace(4, 8, 10)
yi = np.linspace(1, 4, 10)
zi = matplotlib.mlab.griddata(x, y, z, xi, yi, interp='linear')
plt.contour(xi, yi, zi)

(b) Finally, one can plot a contour completely without the use of a quadrilateral grid. This can be done using tricontour.

plt.tricontour(x,y,z)

An example comparing the latter two methods is found on the matplotlib page.



来源:https://stackoverflow.com/questions/42702920/plotting-isolines-contours-in-matplotlib-from-x-y-z-data-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!