如何使用matplotlib将具有我自己的颜色的渐变颜色图例添加到水平条形图中?

问题描述

我正在尝试为图形添加渐变色图例,但到目前为止,我尝试的所有操作都失败了...

有我的代码

colors = dict(zip(
    [0,1,2,3,4],["#000000","#E30613","#FF9933","#3399FF","#00CC66"]))
group_lk = comparative_cases_democracy.set_index('location')['score'].to_dict()


fig,ax = plt.subplots(figsize=(15,20))
def draw_barchart(df,value):
    df = df.sort_values(by=value,ascending=True).tail(20)
    ax.clear()
    ax.barh(df['location'],df[value]*100,color=[colors[group_lk[x]] for x in df['location']])
    dx = df[value].max() / 100 + 0.05
    for i,(values,name) in enumerate(zip(df[value]*100,df['location'])):
        ax.text(values-dx,i,name,color='#FFFFFF',size=14,weight=600,ha='right',va='center')
       
        ax.text(values+dx,"{:.02f}".format(values),ha='left',va='center')
    # ... polished styles
    
    ax.text(0,1.03,'Percentage (x100) of deaths',transform=ax.transAxes,size=12,color='#777777')

    ax.xaxis.set_ticks_position('top')
    ax.tick_params(axis='x',colors='#777777',labelsize=12)
    ax.set_yticks([])
    ax.margins(0,0.01)
    ax.grid(which='major',axis='x',linestyle='-')
    ax.set_axisbelow(True)
    ax.text(0,1.05,'Liability and Covid-19 numbers',size=24,ha='left')
    ax.text(1,'by Célia Bayet',color='#777777',bBox=dict(facecolor='white',alpha=0.8,edgecolor='white'))
        
    plt.Box(False)
    
draw_barchart(comparative_cases_democracy,'percentage_deaths')

我试图在我的barh中添加cmap,但是显然这不是有效的参数。 我也想使用自己的颜色并以此创建渐变色,这可能吗?

感谢您的帮助!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)