简体   繁体   中英

apply color map to mpl_toolkits.mplot3d.Axes3D.bar3d

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 (ie 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

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:

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 .

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()

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM