How to build a collection of 3D patches in matplotlib?

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

In 2D, I would make a collection of patches and add it to the axes. In 3D, I have problems with the appearance of patches, not to mention orienting 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, that is, the color of the face of the patches, regardless of how I rotate the plot. If I set facecolor='none' in a call to PatchCollection() , an empty Axes3D appears.

Things I tried:

  • If I use CircleCollection instead of PatchCollection , no patches appear at all.
  • The zs parameter in the call to patch_collection_2d_to_3d() odd; I would expect to set 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 them give an error:

    ValueError: setting an array element with a sequence.

  • To orient the patches in different ways, I expected that I could pass something like zdir=['x', 'y', 'z'] , but the results do not differ from whether I pass it either 'z' or ['z'] .

  • I also expected that I could do ax.add_collection3d(circles, zs=[0, 0, 0], zdir=['x', 'y', 'z']) instead of converting the collection of patches from 2d to 3d, but this also causes an error:

    AttributeError: 'Patch3DCollection' object does not have the 'set_sort_zpos' attribute

+8
python matplotlib mplot3d
source share
1 answer
 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() 
+11
source share

All Articles