定义Matplotlib 3D条形图的颜色

时间:2016-07-12 20:21:03

标签: python matplotlib 3d jupyter-notebook mplot3d

我无法找到在我的iPython笔记本中为matplotlib中的3d条形图设置cmap(或颜色)的正确方法。我可以在X和Y平面上正确设置我的图表(28 x 7标签),并带有一些随机Z值。该图很难解释,一个原因是x_data标签[1,2,3,4,5]的默认颜色都是相同的。

以下是代码:

%matplotlib inline
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as npfig = plt.figure(figsize=(18,12))

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

x_data, y_data = np.meshgrid(np.arange(5),np.arange(3))
z_data = np.random.rand(3,5).flatten()

ax.bar3d(x_data.flatten(),
y_data.flatten(),np.zeros(len(z_data)),1,1,z_data,alpha=0.10)

产生以下图表:

enter image description here

我不想手动为标签x_data定义颜色。如何为x_data中的每个标签设置不同的“随机”cmap颜色,仍然保持

  

ax.bar3d

参数?以下是使用

的变体
  

ax.bar

和不同的颜色,但我需要的是 ax.bar3d enter image description here

1 个答案:

答案 0 :(得分:5)

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

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

x_data, y_data = np.meshgrid(np.arange(5),np.arange(3))
z_data = np.random.rand(3,5)
colors = ['r','g','b'] # colors for every line of y

# plot colored 3d bars
for i in xrange(3):  # cycle though y 
    # I multiply one color by len of x (it is 5) to set one color for y line
    ax.bar3d(x_data[i], y_data[i], z_data[i], 1, 1, z_data[i], alpha=0.1, color=colors[i]*5)
    # or use random colors
    # ax.bar3d(x_data[i], y_data[i], z_data[i], 1, 1, z_data[i], alpha=0.1, color=[np.random.rand(3,1),]*5)
plt.show()

结果: enter image description here

相关问题