问题描述
我在matplotlib中有一个3D条形图,其中总共有165条,现在非常混乱.
I have a 3D bar plot in matplotlib which consists of a total 165 bars and at the moment it is quite chaotic.
.
我想根据谨慎的z值(0、1、2)更改条形的颜色.
I would like to change the colour of the bars based on the discreet z-values: 0,1,2.
我知道可以使用.
还有一个关于如何根据值更改条形颜色的问题:定义Matplotlib 3D条形图的颜色
And there is also a question on how to change bar colour based on values:Defining colors of Matplotlib 3D bar plot
我不确定我是否能完全理解给出的答案,但是在这种情况下我无法使其正常工作.
I am not sure If i perfectly comprehend the given answer but I cannot make it work in this case.
代码是:
,color可以是一个数组,每个条带一种颜色.As seen from the documentation of bar3d, color can be an array, with one color per bar.
这使得在一次调用bar3d的所有条上着色变得非常容易;我们只需要将data数组转换为可以使用颜色图完成的颜色数组
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()))(请注意,颜色表的值介于0到1之间,因此我们需要将这些值归一化到该范围内.)
(Note, that a colormap takes values between 0 and 1, so we need to normalize the values into this range.)
完整示例:
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()这篇关于根据值更改matplotlib中3D条形图中的条形颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!