2

I would like to make a 3D plot in matplotlib. I have 6 points with x, y and z coordinates. I plotted them and I got this:

3D Plot without filling

But my target is plot where surface between blue lines will be colour-filled.

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

plt.rcParams['svg.fonttype'] = 'none'  # during export plots as .svg files, text is exported as text (default text is exported as curves)

data = np.loadtxt('D:\PyCharm\File1.txt', skiprows=1)

x = data[:, 0]
y = data[:, 1]
z = data[:, 2]    

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.plot(x, y, z)

axes = plt.gca()
axes.set_xlim(5712000, 5716000)
axes.set_ylim(5576000, 5579000)
axes.set_zlim(-1000, -600)
axes.set_xlabel('X')
axes.set_ylabel('Y')
axes.set_zlabel('Z')

plt.tight_layout()
plt.show()

And I tried tri-surface plot:

ax.plot_trisurf(x, y, z)

But the shape is not correct:

Tri-surface plot

Edit: About my data: it's text file, which looks like:

X   Y   Z
5714397 5576607 -1008
5713159 5577871 -999
5713465 5577909 -1014
5714156 5577428 -1022
5714410 5577789 -1035
5715057 5577407 -1036
5714397 5576607 -1008

Second and last rows are the same, but I tried with another file, in which I deleted last row. Plots were the same as above.

1 Answers1

5

You are using plot to draw the vertices. This gives you a line, as expected. In order to get a filled polygon, use Poly3DCollection.

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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
plt.tight_layout()

x,y,z = np.loadtxt('D:\PyCharm\File1.txt', skiprows=1, unpack=True)

verts = [zip(x, y,z)]
ax.add_collection3d(Poly3DCollection(verts))

ax.set_xlim(5712000, 5716000)
ax.set_ylim(5576000, 5579000)
ax.set_zlim(-1000, -600)
plt.show()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • It works. But I use Python 3, so I had this problem [Plotting 3D Polygons in Python 3](http://stackoverflow.com/questions/37585340/plotting-3d-polygons-in-python-3). Now everything is ok. – Maciej Barnaś Feb 01 '17 at 09:52
  • I needed to change this to `verts = [list(zip(x, y, z))]` for this to work for me. – Scott Jan 29 '22 at 18:19