﻿ python – 根据值在matplotlib中更改3D条形图中的条形颜色 - 代码日志

#### python – 根据值在matplotlib中更改3D条形图中的条形颜色

Defining colors of Matplotlib 3D bar plot

``````   data = [[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]]

ly = len(data[0])
lx = len(data[:,0])
xpos = np.arange(0,lx,1)    # Set up a mesh of positions
ypos = np.arange(0,ly,1)
xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)

xpos = xpos.flatten()   # Convert positions to 1D array
ypos = ypos.flatten()
zpos = np.zeros(lx*ly)

dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = data.flatten()

ys = np.array([float(yi) for yi in y[1:]])

fig = plt.figure()

# all blue bars
#ax.bar3d(xpos,ypos,zpos, dx, dy, dz, color='b')

# try changing color bars

colors = ['r','g','b']
for i in range(0,3):

ax.bar3d(xpos[i], ypos[i], zpos[i], dx, dy, dz[i], alpha=0.1,
color=colors[i])

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

plt.show()
``````
documentation of bar3d可以看出,颜色可以是一个数组,每条颜色一种颜色.

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

(注意,色图的取值介于0和1之间,因此我们需要将值标准化为此范围.)

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