3D 绘图非常适合制作曲面图。在曲面图中,每个点由 3 个变量定义:纬度、经度和高度(X、Y 和 Z)。因此,有两种类型的输入是可能的:
1) 一个矩形矩阵,其中每个单元格代表海拔高度。
2) 一个有 2 列的长格式矩阵,其中每行是一个点。
此示例使用矩形格式作为输入,将其转换为长格式,并绘制以下图:
这篇博客文章我们来解释如何使用并创建一个3d曲面动态图。还显示了如何改变旋转角度以生成不同角度的动画。
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pandas as pd
# 获取data
data = pd.read_csv(r'C:\Users\联想\Downloads\volcano.csv')
# 转换为长格式
df = data.unstack().reset_index()
df.columns = ["X", "Y", "Z"]
#并将旧的列名转换为数字形式
df['X'] = pd.Categorical(df['X'])
df['X'] = df['X'].cat.codes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # Use add_subplot instead of gca
ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.viridis, linewidth=0.2)
# 调整角度
ax.view_init(30, 70)
plt.show()
代码如下(示例):
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
data = pd.read_csv(r'C:\Users\联想\Downloads\volcano.csv')
df=data.unstack().reset_index()
df.columns=["X","Y","Z"]
df['X']=pd.Categorical(df['X'])
df['X']=df['X'].cat.codes
for angle in range(70,166,2):
plt.ioff()
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.viridis, linewidth=0.2)
ax.view_init(30,angle)
filename='C:/Users/联想/OneDrive/桌面/yyy/img'+str(angle)+'.png'
plt.savefig(fname=filename, dpi=96)
plt.gca()
plt.close(fig)
旋转角度,从70旋转到166,每隔两度旋转截图一次。
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
#url = 'https://raw.githubusercontent.com/holtzy/The-Python-Graph-Gallery/master/static/data/volcano.csv'
data = pd.read_csv(r'C:\Users\联想\Downloads\volcano.csv')
df=data.unstack().reset_index()
df.columns=["X","Y","Z"]
df['X']=pd.Categorical(df['X'])
df['X']=df['X'].cat.codes
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.viridis, linewidth=0.2)
plt.show()
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
surf=ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.viridis, linewidth=0.2)
fig.colorbar( surf, shrink=0.5, aspect=5)
plt.show()
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
surf=ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.viridis, linewidth=0.2)
ax.view_init(30, 45)
plt.show()
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.plot_trisurf(df['Y'], df['X'], df['Z'], cmap=plt.cm.jet, linewidth=0.01)
plt.show()