【问题标题】:ggplot/plotnine - adding a legend from geom_text() with specific colorggplot/plotnine - 从 geom_text() 添加具有特定颜色的图例
【发布时间】:2020-03-18 18:50:41
【问题描述】:

我有这个数据框:

df = pd.DataFrame({'Segment': {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'A', 5: 'B', 6: 'C', 7: 'D'},
                  'Average': {0: 55341, 1: 55159, 2: 55394, 3: 56960, 4: 55341, 5: 55159, 6: 55394, 7: 56960},
                  'Order': {0: 0, 1: 1, 2: 2, 3: 3, 4: 0, 5: 1, 6: 2, 7: 3},
                  'Variable': {0: 'None', 1: 'None', 2: 'None', 3: 'None', 4: 'One', 5: 'One', 6: 'One', 7: 'One'},
                  '$': {0: 40.6, 1: 18.2, 2: 78.5, 3: 123.3, 4: 42.4, 5: 24.2, 6: 89.7, 7: 144.1},
                  'ypos': {0: 96.0, 1: 55.4, 2: 181.2, 3: 280.4, 4: 96.0, 5: 55.4, 6: 181.2, 7: 280.4},
                  'yticks': {0: 20.3,1: 9.1,2: 39.25,3: 61.65,4: 21.2,5: 12.1,6: 44.85,7: 72.05}})

我绘制了这个:

(ggplot(df, aes(x="Segment", y="$", ymin=0, ymax=300, fill="Variable"))
 + geom_col(position = position_stack(reverse = True), alpha=0.7)
 + geom_text(aes(x = "Segment", y = "ypos", label = "Average"), size=8, format_string="Average: \n ${:,.0f} CLP")
 + geom_text(aes(label = "$"), show_legend=True, position=position_stack(vjust = 0.5), size=8, format_string="%s"%(u"\N{dollar sign}{:,.0f} MM"))
)

我一直在寻找一种方法来添加Average 的图例,然后(然后)我将删除条上的“平均”字样,只留下数字。但是,为了便于理解,附加图例的颜色应与平均值颜色相同(可以是黄色、橙色或任何其他颜色,但不能使用红色或天蓝色,因为这些颜色已被使用)

【问题讨论】:

    标签: pandas ggplot2 plotnine


    【解决方案1】:

    您可以将颜色作为变量添加到geom_text

    import plotnine
    from plotnine import ggplot, geom_col, aes, position_stack, geom_text, scale_color_brewer, guides, guide_legend
    
    (ggplot(df, aes(x="Segment", y="$", ymin=0, ymax=300, fill="Variable"))
     + geom_col(position = position_stack(reverse = True), alpha=0.7)
     + geom_text(aes(y = "ypos",color="Segment",label = "Average"), size=8, 
                 show_legend=True,format_string="${:,.0f} CLP")
     + geom_text(aes(label = "$"), show_legend=True, position=position_stack(vjust = 0.5), 
                 size=8, format_string="%s"%(u"\N{dollar sign}{:,.0f} MM"))
     + scale_color_brewer(type='qual', palette=2)
     + guides(color=guide_legend(title="Averages"))
    )
    

    【讨论】:

    • 并将 x="Segment" 更改为 color="Segment" 并将 x= 留空。成功了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    相关资源
    最近更新 更多