plot contours/contours in matplotlib from (x, y, z) datasets
Hi all, I’m
new to programming and I’m trying to do something that might be very obvious, but for 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 want to use matplotlib to plot contours of z-data (pH) on an xy (distance, depth) grid. Is there any way? Thank you.
Solution
The solution will depend on how the data is organized.
Data on a grid of rules
If the x
and y
data already have a grid defined, they can be easily reshaped to a quadrilateral mesh. For example
#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 be plotted as > used in contour
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) If the data is not on a quad grid, data can be inserted on the grid. matplotlib itself provides a way to use 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, contours can be drawn completely without using a quad grid. This can be done using tricontour
plt.tricontour(x,y,z)
An example comparing the latter two approaches can be found on the matplotlib page