Contour Plot in Python [Duplicate]

Contour Plot in Python [Duplicate]

I have 3 lots of data. These are x and y values as well as a temperature value for each xy point. I would like to plot each point and interpolate the area between points to get a continuous surface. The issue I have is specifying the temperature values. I can't get it to work with an equal number of x,y and z (temperature) values and all the examples I can find online use a function of x and y to create z or have z values for every point on an xy grid. Is there a simple way to do this?

import numpy as np
import matplotlib.pyplot as plt

fig, axs = plt.subplots()

x = np.linspace(0, 1, 100)
y = np.linspace(0,1,100)
X, Y = np.meshgrid(x, y)
#Z = np.sin(X)*np.sin(Y)  # want to specify not an equation
Z = np.linspace(1,2,100)
levels = np.linspace(-1, 1, 40)
cs = axs.contourf(X, Y, Z, levels=levels)
fig.colorbar(cs, ax=axs, format="%.2f")
plt.show()

Update:

Here is what I have so far. I still need to work out a good method to fill in the area between points. Does anyone have any ideas?

import numpy as np
import matplotlib.pyplot as plt

fig, axs = plt.subplots()

# create a grid in the correct shape / size
x = np.linspace(0, 1, 3)
y = np.linspace(0,1,3)
X, Y = np.meshgrid(x, y)

# specify and change the relevent areas
y = [1,2,0]  # location of point in x direction
x =[2,1,1]  #location of point in y direction
z = [40,30,20]  #temperature
Z = np.arange(1,10).reshape((3,3))
Z[y,x] = z

levels = np.linspace(0, 40, 40)
cs = axs.contourf(X, Y, Z, levels=levels)
fig.colorbar(cs, ax=axs, format="%.2f")
plt.show()
2

1 Answer

The reason people use a function of x and y is because your Z value has to be a function of x and y. In your test code Z is 1D but it needs to be 2D to plot the contours.

If you have Z (temperature) values that have the same shape as your x and y coordinates then it should work.

x = np.linspace(0, 1, 100)
y = np.linspace(0,1,100)

X, Y = np.meshgrid(x, y)
#Z = np.sin(X)*np.sin(Y)  # want to specify not an equation
Z = np.linspace(1,2,100)

print X.shape

print Z.shape

(100L,100L)

(100L)

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.