Interchange location of y and z axis in 3D matplotlib plot

Question:

By default, plotting a set of points (or whatever) in 3D with matplotlib, locates the z axis vertically, as seen here (code below):

enter image description here

I need to interchange the z and y axis, so that that y axis is shown vertically.

I’ve looked around but found no way to tell matplotlib to do this.

Add: I do not want to have to resort to a hack where I interchange the data and labels. This is a simple 3 points 3D plot, but I have to plot much more complicated surfaces. I’m looking for a general solution, not just something that works with scatter plots. A simple way to tell matplotlib to put the y axis vertically instead of the z axis is the clean way to do it.


MWE

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D


fig = plt.figure()
ax = Axes3D(fig)

ax.scatter([0.2, 0.5, 0.8], [2.3, 0.47, 1.], [2.1, 5.3, 0.7])

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()
Asked By: Gabriel

||

Answers:

One possibility is to interchange the position of y and z in the data and label accordingly. instead of

ax.scatter([0.2, 0.5, 0.8], [2.3, 0.47, 1.], [2.1, 5.3, 0.7])

use

ax.scatter([0.2, 0.5, 0.8], [2.1, 5.3, 0.7], [2.3, 0.47, 1.])

and label as ax.set_ylabel('z') and ax.set_zlabel('y')

Answered By: innoSPG

I don’t think that this is currently possible. ax.view_init() would need to accept a third angle too.
I opened an issue over at github, https://github.com/matplotlib/matplotlib/issues/14453#issue-452397120, let’s hope someone is committed to implement this feature.

Update

The third view angle was recently implemented and has been merged into the matplotlib main branch: https://github.com/matplotlib/matplotlib/pull/21426

It should appear in Matplotlib 3.6.0.

Answered By: Bastian

Matplotlib 3.6.0 is now out, and allows you to set this third view angle via the command ax.view_init(elev, azim, roll). See the official documentation.

enter image description here

Answered By: Scott
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.