使用 plotnine 时基于 Pandas 数据框中值的颜色条

问题描述

我正在尝试使用 plotnine 构建瀑布图。我想将起始条和结束条着色为灰色(理想情况下我想指定十六进制颜色),增加为绿色,减少为红色。

以下是一些示例数据和我当前的绘图。我试图将 fill 设置为 Pandas 列 colour,但条形全是黑色。我也将 fill 放在 geom_segment 中,但这也不起作用。

df = pd.DataFrame({})
df['label'] = ('A','B','C','D','E')
df['percentile'] = (10)*5
df['value'] = (100,80,90,110,110)
df['yStart'] = (0,100,0)
df['barLabel'] = ('100','-20','+10','+20','110')
df['labelPosition'] = ('105','75','95','115','115')
df['colour'] = ('grey','red','green','grey')

p = (ggplot(df,aes(x=np.arange(0,5,1),xend=np.arange(0,y='yStart',yend='value',fill='colour'))
    + theme_light(6)
    + geom_segment(size=10)
    + ylab('value')
    + scale_y_continuous(breaks=np.arange(0,141,20),limits=[0,140],expand=(0,0))
)

enter image description here

编辑

根据 teunbrand 将 fill 更改为 color评论我有以下几点。如何指定实际颜色,最好是十六进制格式?

enter image description here

解决方法

为了结束这个问题,在解决方案的评论中感谢 teunbrand。

{{ optional($customer->BillAddr)->Line1 }} 具有 geom_segment() 美感但不是 colour 美感。将 fill 替换为 fill='colour'

Plotnine 将为条形使用默认颜色。如果 colour='colour' 列的内容是文字颜色,请使用 scale_color_identity(),或使用 DataFrame 手动指定元组或颜色列表。两种形式都接受十六进制颜色。