Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add labels to bar plot

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading