b-ryce
b-ryce

Reputation: 5828

r add background color to geom_label()

I have a function for creating a bar chart that looks like this:

my_bar_chart <- function(data, column, title, change_order=FALSE){
  out <-  data %>% 
    group_by({{column}}) %>% 
    summarize(count = n()) %>% 
    mutate(percent = count/sum(count),
           !! rlang::enquo(column) := if(change_order)
             reorder({{column}}, -count, FUN=identity) else {{column}} )
  ggplot(out, aes(x={{column}}, y=count, fill={{column}})) +
    xlab(title)+
    geom_col() +
    guides(fill=FALSE) + 
    geom_label(aes(label = paste0(round(100 * percent, 1), "%")))
}

my_bar_chart(d, audio_in_total, "EA5 Audio Inputs")

But my labels are coming out with their background color the same as the column, and hard to read I can't read them. enter image description here

I tried adding a white background like this, but it didn't work (it added a legend with the value of "white"):

geom_label(aes(label = paste0(round(100 * percent, 1), "%"), colour = "white"))

What is a better way to get the label background to be white?

My data has a column that looks like this:

audio_in_total
0
1
0
2
0

Upvotes: 5

Views: 2236

Answers (1)

Dave Gruenewald
Dave Gruenewald

Reputation: 5689

Try to put the fill outside of the aes() call:

geom_label(aes(label = paste0(round(100 * percent, 1), "%")), fill = "white")

Upvotes: 4

Related Questions