Grids of Subplots with 3D Polycollection

让人想犯罪 __ 提交于 2020-02-26 02:14:50

问题


Create a grid of 3D Subplots using mplot3d Polycollection (or another mplot3d library)

Here is a simple mplot3d example (you can see here: https://matplotlib.org/2.0.2/examples/mplot3d/polys3d_demo.html) :

from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
xs = np.arange(0, 10, 0.4)
verts = []
zs = [0.0, 1.0, 2.0, 3.0]
for z in zs:
    ys = np.random.rand(len(xs))
    ys[0], ys[-1] = 0, 0
    verts.append(list(zip(xs, ys)))
poly = PolyCollection(verts,lw=1, closed=False)
poly.set_alpha(0.7)
ax.add_collection3d(poly, zs=zs, zdir='y')
ax.set_xlabel('X')
ax.set_xlim3d(0, 10)
ax.set_ylabel('Y')
ax.set_ylim3d(-1, 4)
ax.set_zlabel('Z')
ax.set_zlim3d(0, 2)
plt.show()

Now I have a large number of slices and I want to plot them within several subfigures. I already tried some codes (see for example https://jakevdp.github.io/PythonDataScienceHandbook/04.08-multiple-subplots.html), including something like that :

verts = []
zs = np.arange(1000)
for z in zs:
    df = rfft(tiles[z])
    ys = 2.0/100 * np.abs(df[0:100//2])
ys[0], ys[-1] = 0, 0
verts.append(list(zip(xs, ys)))
fig = plt.figure(figsize=(15,8))
for i in range(40):
    plt.subplot(20, 2, i)
    ax = fig.gca(projection='3d') 
    poly = PolyCollection(verts[i*25:(i+1)*25],lw=1)
    ax.add_collection3d(poly, zs=np.arange(25), zdir='y')

But as a result, I get nothing but a normal vertical succession of figures. No subfigure at all. So how to combine subplotting with 3D plotting (here using polycollection) Thanks


回答1:


I would create the axes using plt.subplots() passing the argument subplot_kw=dict(projection='3d') to directly create all the subplots as Axes3D objects. Then it's just a matter of iterating over the axes and populating them as you see fit.

xs = np.arange(0, 10, 0.4)
verts = []
zs = [0.0, 1.0, 2.0, 3.0]
for z in zs:
    ys = np.random.rand(len(xs))
    ys[0], ys[-1] = 0, 0
    verts.append(list(zip(xs, ys)))


fig, axs = plt.subplots(2,2,figsize=(10,10), subplot_kw=dict(projection='3d'))
for i,ax in enumerate(axs.flat):
    poly = PolyCollection(verts,lw=1, closed=False)
    poly.set_alpha(0.7)
    ax.add_collection3d(poly, zs=zs, zdir='y')
    ax.set_xlabel('X')
    ax.set_xlim3d(0, 10)
    ax.set_ylabel('Y')
    ax.set_ylim3d(-1, 4)
    ax.set_zlabel('Z')
    ax.set_zlim3d(0, 2)
    ax.view_init(elev=10.+i*10, azim=25+i*25)



来源:https://stackoverflow.com/questions/57286320/grids-of-subplots-with-3d-polycollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!