Home > Mobile >  Add labels to bar plot
Add labels to bar plot

Time:10-12

I have a bar chart with percentages of responses on a Likert-type scale.

I've computed the frequency (%) of each response.

I'd like to print the text of that percentage over the corresponding bar in the chart.

However, when I add geom_text(aes(label = freq), vjust = 1.5) it smashes down the bars instead of printing the text over them.

Any suggestions on what I'm doing wrong?

data<-tribble(
  ~Question, ~Response, ~Count, ~Freq,
  "Q1", "SD", 4, 0.065,
  "Q1", "D", 3, 0.048,
  "Q1", "N", 17, 0.274,
  "Q1", "A", 29, 0.468,
  "Q1", "SA", 9, 0.145,
)

## This gives me the graph I want
data %>%
  ggplot(aes(fill=Response, x = Count, y = Question))   
  geom_bar(position="fill", stat="identity", width=0.5)   
  scale_fill_brewer(palette="PRGn")  
  theme_minimal()

## But if I add in geom_text to print the frequencies, it messes it up
data %>%
  ggplot(aes(fill=Response, x = Count, y = Question))   
  geom_bar(position="fill", stat="identity", width=0.5)   
  scale_fill_brewer(palette="PRGn")  
  theme_minimal()  
  geom_text(aes(label = Freq*100), vjust = 1.5)

enter image description here

CodePudding user response:

You need to use the percentages, not the absolute values in your geom_bar.

library(tidyverse)


data %>%
  ggplot(aes(fill=Response, x = Freq, y = Question))   
  geom_bar(position="fill", stat="identity", width=0.5)   
  scale_x_continuous(labels = scales::percent)   # change x-axis to percentage
  geom_text(aes(label = paste0(Freq*100,"%")), position = position_stack(vjust = 0.6))  
  scale_fill_brewer(palette="PRGn")  
  theme_minimal()

  • Related