问题描述
当我用鼠标旋转我的 Matplotlib 3D 绘图时,如何保存视角/相机位置,并在下次运行脚本时使用这些值以编程方式设置视角?
How can I save the viewing angle / camera position when I've rotated my Matplotlib 3D plot with my mouse, and use those values to set the viewing angle programmatically the next time I run my script?
推荐答案
TL;DR
视角以elev
和azim
名称存储在图形的axis-object 中,视图可以通过plt.gca 设置().view_init(elev, azim)
.
TL;DR
The viewing angles are stored in the axis-object of the figure under the names elev
and azim
, and the view can be set with plt.gca().view_init(elev, azim)
.
导入库并生成要绘制的数据:
Import libraries and generate data to plot:
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')
我们显示该图并调整视角,直到看起来不错为止.一旦将其关闭,便会打印出仰角和方位角变量.
We show the plot and adjust the viewing angles until it looks nice.Once we close it, the elevation and azimuth-angle variables are printed.
plt.show()
print('ax.azim {}'.format(ax.azim))
print('ax.elev {}'.format(ax.elev))
一旦有了这些值,就可以使用
Once you have those values, you can set the viewing angles programmatically using
ax.view_init(elev, azim)
示例图 - 在调整到 ax.azim = -164.5 和 ax.elev = 51.25 之前和之后.
Example plots — before adjusting and after adjusting to ax.azim = -164.5 and ax.elev = 51.25.
此外,这里有一个完整的脚本,如果您想尝试一下,可以将其复制粘贴:
Also, here's an entire script, which you can copy paste to if you'd like to try it out:
#!/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))
这篇关于在Matplotlib 3D图中获取视角/摄像机角度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!