Defining colors of Matplotlib 3D bar plot

梦想与她 提交于 2019-12-10 22:16:48

问题


I can't figure out the right way to set a cmap (or colors) for a 3d bar plot in matplotlib in my iPython notebook. I can setup my chart correctly (28 x 7 labels) in the X and Y plane, with some random Z values. The graph is hard to interpret, and one reason is that the default colors for the x_data labels [1,2,3,4,5] are all the same.

Here is the code:

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

Which produces the following chart:

I don't want to define the colors manually for the labels x_data. How can I set up different 'random' cmap colors for each of the labels in x_data, still keeping the

ax.bar3d

parameter? Below is a variation using

ax.bar

and different colors, but what I need is ax.bar3d.


回答1:


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

Result:



来源:https://stackoverflow.com/questions/38338221/defining-colors-of-matplotlib-3d-bar-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!