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?
Asked
Active
Viewed 1.4k times
7
-
2[This answer](https://stackoverflow.com/a/41190487/4124317) shows how to synchronize the camera position between two plots. You can use this and instead of synchronizing, just print the `azim` and `elev` to the console. – ImportanceOfBeingErnest Dec 02 '17 at 18:00
1 Answers
20
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)
.
Elaborate answer and example
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
Now plot the 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')
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)
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))

AllanLRH
- 1,124
- 1
- 12
- 23