1

I can’t find out how to get data from an mplot3d graph. Something similar to the 2D style:

line.get_xdata()

Is it possible?

2 Answers 2

4

Line3D

You can get get the original data from the (private) _verts3d attribute

xdata, ydata, zdata = line._verts3d
print(xdata)

Complete example

import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure()
ax = fig.gca(projection='3d')

# Prepare arrays x, y, z
x = np.arange(5)
y = np.arange(5)*4
z = np.arange(5)*100

line, = ax.plot(x, y, z, label='curve')

fig.canvas.draw()

xdata, ydata, zdata = line._verts3d
print(xdata)  # This prints [0 1 2 3 4]

plt.show()

Some explanation: The problem with get_data or get_xdata is that it will return the projected coordinates once the figure is drawn. So while before drawing the figure, line.get_xdata() would indeed return the correct values, after drawing, it would return something like

[ -6.14413090e-02  -3.08824862e-02  -3.33066907e-17   3.12113190e-02 6.27567511e-02]

in the above example, which is the x component of the 3D coordinates projected onto 2D.


There is a pull request to matplotlib, which would allow to get the data via methods get_data_3d. This is still not merged, but might allow the above to be done without using private arguments in a future version of matplotlib.

Poly3DCollection

For a plot_surface plot this looks similar, except that the attribute to look at is the ._vec

surf = ax.plot_surface(X, Y, Z)
xdata, ydata, zdata, _ = surf._vec
print(xdata)
Sign up to request clarification or add additional context in comments.

4 Comments

Excellent answer, and I will accept. But I was not specific enough. I have problems with a plot_surface graph. Is there a similar way for surface graphs?
Short follow up: The data has lost its dimensions. It’s now a one dimensional nearest. I want to use the data to make a replot. How do I retrieve the original dimensions?
I'm not sure if you can easily do that actually.
FYI: the PR has been merged and the feature will be in the next release it seems so.
0

This issue was filed on Github and there is contribution that adds new get_data_3d and set_data_3d methods. Unfortunately, these changes is likely not yet available in distributions. So you might have to continue using private variable line._verts3d.

See more here: https://github.com/matplotlib/matplotlib/issues/8914

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.