Detailed explanation of drawing three-dimensional graphs in Python

Use Python to draw 3D graphs

Goal: draw image z 2 = x 2 + y 2 z^2 = x^2 + y^2z2=x2+y2

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D #绘制3D图案

The first step in drawing a surface is to create a two-dimensional grid. In Python, we use meshgrid()functions, and this function is also used in matlab.

Create data: first create x and y, their range is (-1,1)

x = np.linspace(-1,1,100)
y = np.linspace(-1,1,50)

Then call the meshgrid function in numpy to perform meshing operations.

x_,y_ = np.meshgrid(x,y,indexing='ij') 

x_, y_ returns a grid array. By printing the shapes of x_ and y_, you can see that x_, y_ are two-dimensional arrays of (100*50), that is, the length of the array x is multiplied by the length of the array y

print(x_.shape,y_.shape)  
(100, 50) (100, 50)

Gridding unifies the dimensions of X and Y. When performing array operations, more data is involved and the scope is wider.

z_ = x_**2 + y_**2

draw graphics

plt.figure(): custom image.add_subplot
(): add subgraph.plot_surface
(): draw surface.colorbar
(): add color bar

fig = plt.figure(figsize=(12,8),facecolor='white') #创建图片
sub = fig.add_subplot(111,projection='3d')# 添加子图,
surf = sub.plot_surface(x_,y_,z_,cmap=plt.cm.brg) #绘制曲面,并设置颜色cmap
cb = fig.colorbar(surf,shrink=0.8,aspect=15) #设置颜色棒


sub.set_xlabel(r"$x$")
sub.set_ylabel(r"$y$")
sub.set_zlabel(r"$z$")
plt.show()

full code

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D #绘制3D图案

x = np.linspace(-1,1,100)
y = np.linspace(-1,1,50)
x_,y_ = np.meshgrid(x,y,indexing='ij') 
z_ = x_**2 + y_**2
fig = plt.figure(figsize=(12,8),facecolor='white') #创建图片
sub = fig.add_subplot(111,projection='3d')# 添加子图,
surf = sub.plot_surface(x_,y_,z_,cmap=plt.cm.brg) #绘制曲面,并设置颜色cmap
cb = fig.colorbar(surf,shrink=0.8,aspect=15) #设置颜色棒

sub.set_xlabel(r"$x$")
sub.set_ylabel(r"$y$")
sub.set_zlabel(r"$z$")
plt.show()

Please add a picture description

Guess you like

Origin blog.csdn.net/qq_45176548/article/details/127998794