简体   繁体   中英

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!

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 , ie, 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()

图像在这里

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()

在此处输入图片说明

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM