Skip to content Skip to sidebar Skip to footer

Change Bar Color In A 3d Bar Plot In Matplotlib Based On Value

I have a 3D bar plot in matplotlib which consists of a total 165 bars and at the moment it is quite chaotic. . I would like to change the colour of the bars based on the discre

Solution 1:

As seen from the documentation of bar3d, color can be an array, with one color per bar.

This makes it quite easy to colorize all bars in a single call to bar3d; we just need to convert the data array to an array of colors which can be done using a colormap,

colors = plt.cm.jet(data.flatten()/float(data.max()))

(Note, that a colormap takes values between 0 and 1, so we need to normalize the values into this range.)

Complete example:

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

data = np.array([ [0, 0, 0, 2, 0, 0, 1, 2, 0, 0, 0],
         [0, 0, 2, 2, 0, 0, 0, 0, 2, 0, 0],
         [1, 0, 2, 2, 1, 2, 0, 0, 2, 0, 2],
         [1, 0, 2, 2, 0, 2, 0, 2, 2, 2, 2],
         [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
         [2, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2],
         [0, 2, 2, 0, 2, 2, 2, 2, 2, 2, 2],
         [1, 2, 0, 0, 2, 1, 2, 2, 0, 0, 2],
         [0, 0, 2, 1, 0, 0, 2, 0, 0, 0, 0],
         [2, 1, 2, 2, 0, 0, 0, 2, 0, 0, 2],
         [2, 2, 2, 0, 2, 0, 0, 0, 2, 2, 2],
         [2, 2, 0, 0, 2, 2, 2, 2, 2, 0, 0],
         [2, 2, 1, 2, 0, 0, 0, 2, 2, 2, 0],
         [2, 0, 0, 2, 0, 0, 2, 2, 2, 2, 2],
         [2, 0, 0, 2, 0, 2, 2, 2, 2, 2, 2]])


ypos, xpos  = np.indices(data.shape) 

xpos = xpos.flatten()   
ypos = ypos.flatten()
zpos = np.zeros(xpos.shape)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

colors = plt.cm.jet(data.flatten()/float(data.max()))
ax.bar3d(xpos,ypos,zpos, .5,.5,data.flatten(), color=colors)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()

enter image description here

Post a Comment for "Change Bar Color In A 3d Bar Plot In Matplotlib Based On Value"