Alexander K
Alexander K

Reputation: 137

Best way to plot a 2d contour plot with a numpy meshgrid

i'm looking for the best way to create a contour plot using a numpy meshgrid.

I have excel data in columns simplyfied looking like this:

x data values: -3, -2, -1, 0, 1, 2 ,3, -3, -2, -1, 0, 1, 2, 3
y data values:  1,  1,  1, 1, 1, 1, 1,  2,  2,  2, 2, 2, 2, 2
z data values:  7 , 5,  6, 5, 1, 0, 9,  5,  3,  8, 3, 1, 0, 4

The x and y values define a 2d plane with the length (x-Axis) of 7 values and depth (y-Axis) of 2 values. The z values define the colour at the corresponing points (more or less a z-Axis).

I've tried:

import matplotlib.pyplot as plt
import numpy as np

x = [-3,-2,-1,0,1,2,3]

y = [1,2]

z = [7,5,6,5,1,0,9,5,3,8,3,1,0,4]

x, y = np.meshgrid(x, y)

A = np.array(z)
B = np.reshape(A, (-1, 2))

fig = plt.figure()
ax1 = plt.contourf(x, y, B)

plt.show()

I'm pretty sure i'm not getting how the meshgrid works. Do i have to use the whole List of x and y values for it to work?

How do i create a rectangular 2d plot with the length (x) of 7 and the depth (y) of 2 and the z values defining the shading/colour at the x and y values?

Thanks in advance guys!

Upvotes: 5

Views: 16426

Answers (3)

Deepak
Deepak

Reputation: 1

def f(x, y):
    return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2, 3 )
y = np.linspace(0, 3, 4)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
plt.contour(X, Y, Z, cmap='RdGy');

Upvotes: 0

jamesoh
jamesoh

Reputation: 382

Try

x_, y_ = np.meshgrid(x, y)
z_grid = np.array(z).reshape(2,7)
fig = plt.figure()
ax1 = plt.contourf(x_,y_,z_grid)
plt.show()

Edit: If you would like to smooth, as per your comment, you can try something like scipy.ndimage.zoom() as described here, i.e., in your case

from scipy import ndimage

z_grid = np.array(z).reshape(2,7)
z_grid_interp = ndimage.zoom(z_grid, 100)
x_, y_ = np.meshgrid(np.linspace(-3,3,z_grid_interp.shape[1]),np.linspace(1,2,z_grid_interp.shape[0]))

and then plot as before:

fig = plt.figure()
ax1 = plt.contourf(x_,y_,z_grid_interp)
plt.show()

image here

Upvotes: 3

Sheldore
Sheldore

Reputation: 39072

This is one way where you use the shape of the meshgrid (X or Y) to reshape your z array. You can, moreover, add a color bar using plt.colorbar()

import matplotlib.pyplot as plt
import numpy as np

x = [-3,-2,-1,0,1,2,3]
y = [1,2]
z = np.array([7,5,6,5,1,0,9,5,3,8,3,1,0,4])

X, Y = np.meshgrid(x, y)
print (X.shape, Y.shape)
# (2, 7) (2, 7) Both have same shape
Z = z.reshape(X.shape) # Use either X or Y to define shape

fig = plt.figure()
ax1 = plt.contourf(X, Y, Z)
plt.colorbar(ax1)
plt.show()

enter image description here

Upvotes: 1

Related Questions