numpy中meshgrid的使用

meshgrid的適用於生成網格型數據,可以接受兩個一維數組生成兩個二維矩陣,對應兩個數組中所有的(x,y)對

例子

x = np.arange(1,4)
x
Out[13]: array([1, 2, 3])
y = np.arange(5,10)
x
Out[15]: array([1, 2, 3])
y
Out[16]: array([5, 6, 7, 8, 9])
z1, z2 = np.meshgrid(x, y)
z1
Out[21]: 
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]])
z2
Out[22]: 
array([[5, 5, 5],
       [6, 6, 6],
       [7, 7, 7],
       [8, 8, 8],
       [9, 9, 9]])
z1.shape
Out[23]: (5, 3)

小結:meshgrid 後生成的二個數組的形狀shape: (y.size, x.size),第一個數組每行都是x,第二個數組每列都是y

繪製3維圖

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# 繪製散點圖
x1 = np.arange(-4, 4, 0.25)
x2 = np.arange(-4, 4, 0.25)
x, y = np.meshgrid(x1, x2)

r = np.sqrt(x ** 2 + y ** 2)
z = np.sin(r)

fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x, y, z)

# 添加座標軸(順序是x, y, z)
ax.set_xlabel('x', fontdict={'size': 10, 'color': 'red'})
ax.set_ylabel('y', fontdict={'size': 10, 'color': 'green'})
ax.set_zlabel('z', fontdict={'size': 10, 'color': 'blue'})

plt.show()

圖像如下
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章