问题描述
使用 mplot3d Polycollection(或其他 mplot3d 库)创建 3D 子图网格
这是一个简单的 mplot3d 示例(您可以在这里看到:
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
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)
这篇关于带有 3D Polycollection 的子图网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!