0

I need to add colorbar on my voxel, where the facecolors base on a array (in my case, the facecolors base on "data" array). This is my script:

x,y,z = np.mgrid[1:10,3:18,0:5]
data = np.random.normal(0,10,[x.shape[0]-1,x.shape[1]-1,x.shape[2]-1])
visiblebox = np.random.choice([True,False],data.shape)
ax = plt.figure().add_subplot(111,projection ='3d')
colors = plt.cm.plasma(data)
ax.voxels(x,y,z,visiblebox,facecolors=colors,alpha = 0.5,edgecolor='k')
plt.colorbar(colors)
plt.show()

i have try this:

fig = plt.figure()
ax = fig.add_subplot(111,projection ='3d')
p = ax.voxels(x,y,z,visiblebox,facecolors=colors,alpha = 0.5,edgecolor='k')
fig.colorbar(p)

But I get error. I am not sure how to get colorbar to work.

Wahyu Hadinoto
  • 198
  • 1
  • 10

1 Answers1

3

Colorbar for matplotlib plot_surface using facecolorsWhen I looked up SO, I found this answer. I'm not sure about the color bar, but I fixed it while looking at the answer and the color bar showed up.

import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib.colors

x,y,z = np.mgrid[1:10,3:18,0:5]
data = np.random.normal(0,10,[x.shape[0]-1,x.shape[1]-1,x.shape[2]-1])
visiblebox = np.random.choice([True,False],data.shape)

ax = plt.figure().add_subplot(111,projection ='3d')
colors = plt.cm.plasma(data)
norm = matplotlib.colors.Normalize(vmin=0, vmax=16)

vox = ax.voxels(x,y,z,visiblebox,facecolors=colors,alpha = 0.5,edgecolor='k')

m = cm.ScalarMappable(cmap=plt.cm.plasma, norm=norm)
m.set_array([])
plt.colorbar(m)

plt.show()
r-beginners
  • 31,170
  • 3
  • 14
  • 32