当我用鼠标旋转Matplotlib 3D绘图时,如何保存视角/摄像机位置,并在下次运行脚本时使用这些值以编程方式设置视角?
答案 0 :(得分:7)
视角存储在图形的轴对象中,名称为azim
和plt.gca().view_init(elev, azim)
,视图可以设置为import matplotlib as mpl # noqa
from mpl_toolkits.mplot3d import Axes3D # noqa
import matplotlib.pyplot as plt
import numpy as np
mpl.style.use('seaborn')
np.random.seed(11)
n = 200
x = y = np.linspace(-10, 10, n)
z = np.random.randn(n)*3 + 2
。
导入库并生成数据以进行绘图:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
现在绘制数据:
plt.show()
print('ax.azim {}'.format(ax.azim))
print('ax.elev {}'.format(ax.elev))
我们展示情节并调整视角,直到看起来不错。 关闭它后,将打印高程和方位角变量。
ax.view_init(elev, azim)
获得这些值后,您可以使用
以编程方式设置视角#!/usr/bin/env pythonw
import matplotlib as mpl # noqa
from mpl_toolkits.mplot3d import Axes3D # noqa
import matplotlib.pyplot as plt
import numpy as np
mpl.style.use('seaborn')
# ****************************************************************************
# * Create data *
# ****************************************************************************
np.random.seed(11)
n = 200
x = y = np.linspace(-10, 10, n)
z = np.random.randn(n)*3 + 2
# ****************************************************************************
# * Plot data *
# ****************************************************************************
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
# # If we knew what angles we wanted to set, these lines will set it
# elev = 42.0
# azim = 105.5
# ax.view_init(elev, azim)
# Show the figure, adjust it with the mouse
plt.show()
# Once the figure is closed, the azimutal angle and the elevation will
# be printed. They may be used as input for ax.view_init(elev, azim)
print('ax.azim {}'.format(ax.azim))
print('ax.elev {}'.format(ax.elev))
示例图 - 在调整之前和调整到ax.azim = -164.5和ax.elev = 51.25之后。
此外,这是一个完整的脚本,如果你想尝试一下,你可以复制粘贴:
{{1}}