I am trying to make a 3D grid plot in Python using Matplotlib. The grid consists of hexahedral cells (with qudrilateral surfaces). The surfaces should be colored according to their height, that is: the z
coordinate. A colorbar should accompany the plot.
Here is an example plotting three surfaces:
from matplotlib import pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np
def getFaceMidpointsZ(pc):
a=[]
for i in pc:
v=0
for j in i:
v=v+j[2]
v=v/4.
a.append(v)
return a
def getColors(m,a):
b=m.to_rgba(a)
return [(i[0],i[1],i[2]) for i in b]
fig = plt.figure()
ax = plt.axes(projection='3d')
P=[(0,0,0),(2,0,0),(2,2,0),(0,2,0),(0,2,2),(2,2,2),(0,0,2)]
F=[[0,1,2,3],[2,3,4,5],[0,3,4,6]]
x = [t[0] for t in P]
y = [t[1] for t in P]
z = [t[2] for t in P]
pc=[[P[i] for i in f] for f in F]
fz=getFaceMidpointsZ(pc)
q = Poly3DCollection(pc, linewidths=1)
m = cm.ScalarMappable(cmap=cm.jet)
m.set_array([min(z),max(z)])
m.set_clim(vmin=min(z),vmax=max(z))
q.set_facecolor(getColors(m,fz))
ax.add_collection3d(q)
fig.colorbar(m)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
ax.set_xlim(min(x),max(x))
ax.set_ylim(min(y),max(y))
ax.set_zlim(min(z),max(z))
ax.view_init(elev=18., azim=-43.)
plt.show()
I am starting to learn Python and Matplotlib, so any comments would be appreciated.