【问题标题】:How to colour a variable on basis of highest and lowest or at some cut off value for 3d Bar graph in python如何根据最高和最低或在python中3d条形图的某个截止值为变量着色
【发布时间】:2020-02-21 11:47:58
【问题描述】:

我想在我的 3D 条形图中基于一些值或梯度从最低到最高值的切割为 z 赋予不同的渐变颜色,即数值变量。我想设置条件说如果 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)

【问题讨论】:

    标签: python graph colormap 3d-mapping


    【解决方案1】:

    bar3dcolor= 参数可以是一个颜色列表,每条有一个条目。可以使用颜色图构建这样的列表。

    这是一个使用平滑范围为条形着色的示例,绿色表示最高,红色表示最低。将颜色图更改为 cmap = plt.cm.get_cmap('RdYlGn', 2) 会将高于平均值的所有条形着色为绿色,其余条形着色为红色。要将拆分条件准确设置为 50,您可以将 norm 更改为 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()
    

    左边是一个颜色范围的例子,右边是一个只有两种颜色的例子:

    【讨论】:

    • hi @JohanC 谢谢你的解决方案,它确实有效,但是如果我想添加条件,你能建议我而不是规范化变量吗(例如,只要观察值大于 50,我想要那个在绿色其他红色颜色条)
    • 要将条件设置为 50,可以使用norm = mcolors.Normalize(0, 100)
    • 如果数据范围是 111-1112,那么我想在 650 处进行切割?
    • colors = ['limegreen' if u > 650 else 'crimson' for u in dz]
    猜你喜欢
    • 2021-03-13
    • 2018-04-25
    • 2019-09-25
    • 2015-12-03
    • 2021-11-24
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多