我想给我的3D条形图中的数值变量不同的渐变颜色,根据从最低值到最高值的一些切割或梯度。我想把条件说,如果dz是>=50,那么绿色条形图其他红色ba。附上的代码,请分享,如果有任何解决方案。
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection = "3d")
ax.set_xlabel("Cumulative HH's")
ax.set_ylabel("Index") 
ax.set_zlabel("# Observations")
xpos = [1,2,3,4,5,6,7,8,9,10,11,12]#
ypos = [2,4,6,8,10,12,14,16,18,20,22,24]#
zpos = np.zeros(12)
dx = np.ones(12)
dy = np.ones(12)
dz = [100,3,47,35,8,59,24,19,89,60,11,25]
colors=['pink']
ax.bar3d(xpos,ypos,zpos,dx,dy,dz,color=colors)

发布于 2020-02-21 20:24:56
bar3d的color=参数可以是一个颜色列表,每个条带只有一个条目。这样的列表可以使用色彩映射表来构建。
下面是一个示例,它使用从绿色到红色的平滑范围为条形图上色。将色彩映射表更改为cmap = plt.cm.get_cmap('RdYlGn', 2)会将所有条形图的颜色设置为高于平均值的绿色,而将其余部分设置为红色。要将拆分条件精确设置为50,可以将法线更改为norm = mcolors.Normalize(0, 100)。
如果只需要几种不同的颜色,最简单的方法是忘记cmap和norm,只需使用:
colors = ['limegreen' if u > 50 else 'crimson' for u in dz]下面是一个完整的示例:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ax.set_xlabel("Cumulative HH's")
ax.set_ylabel("Index")
ax.set_zlabel("# Observations")
xpos = np.arange(1, 13)
ypos = np.arange(2, 26, 2)
zpos = np.zeros(12)
dx = np.ones(12)
dy = np.ones(12)
dz = [100, 3, 47, 35, 8, 59, 24, 19, 89, 60, 11, 25]
cmap = plt.cm.get_cmap('RdYlGn')
norm = mcolors.Normalize(min(dz), max(dz))
colors = [cmap(norm(u)) for u in dz]
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=colors)
plt.show()左边是一个颜色范围的例子,右边是一个只有两种颜色的例子:

https://stackoverflow.com/questions/60338084
复制相似问题