6

There is a 'color' argument to Axes3D's bar3d function which can accept arrays to color individual bars different colors - but how would I apply a color map (i.e. cmap = cm.jet) in the same way as a plot_surface function for example ? This would make a bar of a certain height a color which reflects its height.

http://matplotlib.sourceforge.net/examples/mplot3d/hist3d_demo.html

http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/api.html

Ferguzz
  • 5,777
  • 7
  • 34
  • 41

3 Answers3

7

Following up the answer provided by Ferguzz, here is a more complete/up-to-date solution:

import matplotlib.colors as colors
import matplotlib.cm as cm


dz = height_values
offset = dz + np.abs(dz.min())
fracs = offset.astype(float)/offset.max()
norm = colors.Normalize(fracs.min(), fracs.max())
color_values = cm.jet(norm(fracs.tolist()))
ax.bar3d(xpos,ypos,zpos,1,1,dz, color=color_values)

Please pay attention to the following points:

AMj
  • 71
  • 1
  • 1
3

Here is my solution:

offset = dz + np.abs(dz.min())
fracs = offset.astype(float)/offset.max()
norm = colors.normalize(fracs.min(), fracs.max())
colors = cm.jet(norm(fracs))

ax.bar3d(xpos,ypos,zpos,1,1,dz, color=colors)

The first line is only required if your data goes negative.

Code adapted from here http://matplotlib.sourceforge.net/examples/pylab_examples/hist_colormapped.html.

Ferguzz
  • 5,777
  • 7
  • 34
  • 41
2

You can pass a color array to the facecolors argument, it can set every patches in the surface a color.

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
colors = np.random.rand(40, 40, 4)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=colors,
        linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

plt.show()

enter image description here

HYRY
  • 94,853
  • 25
  • 187
  • 187
  • I am after behaviour which replicates cmap = cm.jet, however there appears to be no such option for bar3d. Edited my question to make this clear. – Ferguzz Aug 14 '12 at 13:07
  • This answer is not useful in terms of the question being asked here (it doesn't treat bars at all) and can probably best be removed. – ImportanceOfBeingErnest Oct 20 '17 at 20:55
  • @ImportanceOfBeingErnest While what you said is true, this answer exactly addressed what I was trying to do, so I think it is better to leave it :). – Schach21 Nov 04 '21 at 22:52