TVP

# Python作图三维等高面

DechinPhy

480

## 等高线作图

``````import matplotlib.pyplot as plt
import numpy as np

plt.style.use('_mpl-gallery-nogrid')

# make data
X, Y = np.meshgrid(np.linspace(-3, 3, 256), np.linspace(-3, 3, 256))
Z = (1 - X/2 + X**5 + Y**3) * np.exp(-X**2 - Y**2)
levels = np.linspace(np.min(Z), np.max(Z), 7)

# plot
fig, ax = plt.subplots()

ax.contour(X, Y, Z, levels=levels)

plt.show()``````

``````# 该函数在z3维度做了断层
def plot3d(distribution, z1, z2, z3, z_level=[0, 5, 10, 15, 20, 25], levels=np.arange(0, 500, 50)):
import matplotlib.pyplot as plt
fig = plt.figure()
idZ = np.array(z_level, np.int32)
for idx in idZ:
Z = z3[idx]
g = ax.contourf(
z1, z2, distribution[:, :, idx],
zdir='z', offset=z3[idx], levels=levels
)
fig.colorbar(g, ax=ax)
gap = (z3[idZ[-1]]-z3[idZ[0]])/10
ax.set_zlim(z3[idZ[0]]-gap,z3[idZ[-1]]+gap)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()``````

## 等高面作图

``````def iso_surface(distribution, z1, z2, z3, show=True, save_file=None, colorbar_min=0., colorbar_max=500.,
opacity=0.4, surface_number=3):
import os
try:
import plotly.graph_objects as go
import plotly.offline as offline
except ImportError:
# 确保plotly正常安装
os.system('python3 -m pip install --upgrade plotly')
import plotly.graph_objects as go
import plotly.offline as offline
# Plotly作图要求数据展平，这里我们手动操作
x, y, z = np.meshgrid(z1, z2, z3)
distribution = distribution.reshape(-1)
fig= go.Figure(data=go.Isosurface(
x=x.reshape(-1),
y=y.reshape(-1),
z=z.reshape(-1),
value=distribution,
isomin=colorbar_min,
isomax=colorbar_max,
opacity=opacity,
surface_count=surface_number
))
if save_file is not None:
import plotly.io as pio
fmt = save_file.split('.')[-1]
# Plotly支持的图片导出格式就是这几种了
if fmt not in ['png', 'jpg', 'jpeg', 'webp', 'svg', 'pdf', 'eps']:
raise ValueError("The format {} is not supported in plotly!".format(fmt))
try:
pio.write_image(fig, format=fmt, file=save_file)
except ValueError:
# 导出图片需要依赖kaleido环境
os.system('python3 -m pip install --upgrade kaleido')
pio.write_image(fig, format=fmt, file=save_file)
# Plotly生成的结果是以html格式保存的，我们做了一个简单的本地备份
if os.path.exists('offline_plot.html'):
os.rename('offline_plot.html', 'offline_plot.html.bak')
# 生成html文件以后选择是否需要打开，默认生成结束之后自动在浏览器打开图像
if show:
offline.plot(fig, filename='offline_plot.html', auto_open=True)
else:
offline.plot(fig, filename='offline_plot.html', auto_open=False)``````

## 参考链接

1. https://matplotlib.org/stable/plot_types/arrays/contour.html#sphx-glr-plot-types-arrays-contour-py

0 条评论

LV.

• 技术背景
• 等高线作图
• 等高面作图
• 总结概要
• 版权声明
• 参考链接