2

I have this dataframe:

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}})

enter image description here

With I plot this:

(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"))
)

enter image description here

I have been looking for a way to add the legend of Average and (then) I will delete the 'Average' words on the bars and leaving just the number. However, for this to be understandable, the additional legend should be the same color as the Average number values (could be yellow, orange, or any other, but no red or sky blue as those colors are already being used)

Chris
  • 2,019
  • 5
  • 22
  • 67

1 Answers1

0

You can just add color as a variable to 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"))
)

enter image description here

StupidWolf
  • 45,075
  • 17
  • 40
  • 72