bios
bios

Reputation: 1027

Matplotlib: Plot 3d data with alpha

I have 3D data, i.e. data.shape=(N,N,N). What I am planning to do is to plot this data in 3D, using different colors to reflect the value of data[x,y,z]. If some value is under a threshold I want this point to be fully invisible (alpha=0). So in this sense I am looking for a "3D contour plot".

Is this even possible with matplotlib?

Thanks for any advice.

I have found a solution in mathematica using ListContourPlot3D. If there is an equivalent for matplotlib please let me know, thanks

Upvotes: 0

Views: 1747

Answers (1)

Rutger Kassies
Rutger Kassies

Reputation: 64463

Its certainly possible, see the example below where 3 nxm grids are plotted above each other. Notice that the middle one has masked data (in this case) above a certain threshold. The alpha can be controlled by using the cmap.set_bad() property of a colormap.

from mpl_toolkits.mplot3d import Axes3D
import mpl_toolkits.mplot3d.art3d as art3d
import numpy as np
import matplotlib.pyplot as plt 

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')
fig.text(.5,.9, 'Fancy plot', ha='center', size=14)

ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_zticklabels([])

cmap=plt.cm.RdYlGn
cmap.set_bad('white', alpha=0)

p = ax.pcolor(x, y, ndvi1data, cmap=cmap)
art3d.poly_collection_2d_to_3d(p, 0)

q = ax.pcolor(x, y, np.ma.masked_where(ndvi2data>100,ndvi2data), cmap=cmap)
art3d.poly_collection_2d_to_3d(q, 5)

o = ax.pcolor(x, y, ndvi3data, cmap=cmap)
art3d.poly_collection_2d_to_3d(o, 10)

ax.set_xlim([x[0,0], x[-1,0]])
ax.set_ylim([y[0,0], y[0,-1]])
ax.set_zlim([0,10])

fig.colorbar(p)

enter image description here

Upvotes: 2

Related Questions