Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get viewing/camera angles in Matplotlib 3D plot?

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?

like image 847
AllanLRH Avatar asked Dec 04 '22 21:12

AllanLRH


1 Answers

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.

Before adjusting the viewing angles After adjusting the viewing angles


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))
like image 67
AllanLRH Avatar answered Dec 06 '22 11:12

AllanLRH