Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - How to plot a 3D patch collection in matplotlib?

I'm trying to make a 3D plot in matplotlib with three circles on it, each centered at the origin and with a radius of 1, pointing in different directions - to illustrate a sphere of radius 1, for example.

In 2D I would make a circle patch collection and add it to the axes. In 3D I'm having trouble getting the patches to show up at all, let alone orient them in different directions.

import matplotlib
import matplotlib.pyplot as P
import mpl_toolkits.mplot3d as M3

fig = P.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
circles = matplotlib.collections.PatchCollection(
    [matplotlib.patches.Circle((0, 0), 1) for count in range(3)],
    offsets=(0, 0))
M3.art3d.patch_collection_2d_to_3d(circles, zs=[0], zdir='z')
ax.add_collection(circles)
P.show()

Running this program fills the entire plot window with blue, i.e. the face color of the patches, no matter how I rotate the plot. If I set facecolor='none' in the PatchCollection() call, then an empty Axes3D shows up.

Things I've tried:

  • If I use a CircleCollection instead of a PatchCollection, no patches show up at all.
  • The zs parameter in the patch_collection_2d_to_3d() call is odd; I would expect to put either zs=0 (one z-coordinate for all three patches) or zs=[0,0,0] (a separate z-coordinate for each patch), but both of those throw an error:

    ValueError: setting an array element with a sequence.

  • To orient the patches differently, I would expect to be able to pass something like zdir=['x', 'y', 'z'] but the results are no different whether I pass that or 'z' or ['z'].

  • I would also have expected to be able to do ax.add_collection3d(circles, zs=[0, 0, 0], zdir=['x', 'y', 'z']) instead of converting the patch collection from 2d to 3d, but that throws an error too:

    AttributeError: 'Patch3DCollection' object has no attribute 'set_sort_zpos'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, PathPatch
from mpl_toolkits.mplot3d import Axes3D 
import mpl_toolkits.mplot3d.art3d as art3d


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

for i in ["x","y","z"]:
    circle = Circle((0, 0), 1)
    ax.add_patch(circle)
    art3d.pathpatch_2d_to_3d(circle, z=0, zdir=i)


ax.set_xlim3d(-2, 2)
ax.set_ylim3d(-2, 2)
ax.set_zlim3d(-2, 2)

plt.show()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...