0
votes

I'm trying to draw a 2D contour plot in matplotlib using xyz data. I have two sets of Z data I want to plot (z_a and z_b). I have been able to plot the data and draw a contour plot however I have been unable to put a scale on either graph (the scale should be for the z data).

When I use the following code I get an error saying 'TypeError: Input z must be a 2D array.' I thought my z data was in an array so I'm not quite sure why I get this error, could anyone shed some light on this problem? Thanks!

import numpy as np
import matplotlib.pyplot as plt

x = [68,77,95,111,120,148,148,148,175,185,200,218,228]
y = [135,190,87,149,226,68,112,187,225,149,87,190,135]


z_a = [22.87,22.87,23.75,22.81,22.94,22.94,22.94,22.81,22.87,23.06,23.06,23.0,23.12]
z_b = [24.06,24.06,24.94,24.0,24.06,24.12,24.19,24.06,24.12,24.25,24.25,24.25,30]

f, ax = plt.subplots(1,2, sharex=True, sharey=True)

ax[0].tricontourf(x,y,z_a, 100) 
ax[0].plot(x,y, 'ko ')

ax[1].tricontourf(x,y,z_b, 100) 
ax[1].plot(x,y, 'ko ')

plt.contourf(x, y, z_a, 8)
contour_labels = plt.contour(x, y, z_a, 8, colors='black', linewidth=.5)

plt.show()
1
The problem is plt.contour takes 2d matrix as an input and You are trying to plot 1d vector z_a. Take a look at examples here.Tony Babarino

1 Answers

0
votes

You can use griddata something like this:

from scipy.interpolate import griddata

x = [68,77,95,111,120,148,148,148,175,185,200,218,228]
y = [135,190,87,149,226,68,112,187,225,149,87,190,135]

z_a = [22.87,22.87,23.75,22.81,22.94,22.94,22.94,22.81,22.87,23.06,23.06,23.0,23.12]
z_b = [24.06,24.06,24.94,24.0,24.06,24.12,24.19,24.06,24.12,24.25,24.25,24.25,30]

f, ax = plt.subplots(1,2, sharex=True, sharey=True)

ax[0].tricontourf(x,y,z_a, 100) 
ax[0].plot(x,y, 'ko ')

ax[1].tricontourf(x,y,z_b, 100) 
ax[1].plot(x,y, 'ko ')

xi = np.linspace(np.min(x), np.max(x), 100)
yi = np.linspace(np.min(y), np.max(y), 100)
zia = griddata((x,y),z_a,(xi[None,:],yi[:,None]),method='linear')
zib = griddata((x,y),z_b,(xi[None,:],yi[:,None]),method='linear')

ax[0].contourf(xi, yi, zia, 8)
contour_labels = ax[0].contour(xi, yi, zia, 8, colors='black', linewidth=.5)
ax[0].clabel(contour_labels,inline=1,inline_spacing=0,fontsize=10,fmt='%1.0f',colors='k')

ax[1].contourf(xi, yi, zib, 8)
contour_labels = ax[1].contour(xi, yi, zib, 8, colors='black', linewidth=.5)
ax[1].clabel(contour_labels,inline=1,inline_spacing=0,fontsize=10,fmt='%1.0f',colors='k')

plt.show()