Search code examples
rggplot2chartsgeom-text

Charts using ggplot() to apply geom_text() in R


In learning of charts plotting in R, I am using the Australian AIDS Survival Data.

To show the genders in survival, I plot 2 charts with these codes:

data <- read.csv("https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/MASS/Aids2.csv")


ggplot(data) +
  geom_bar(aes(sex, fill = as.factor(status)), position = "fill")  +
  scale_y_continuous(labels = scales::percent)

ggplot(data) +
  geom_bar(aes(as.factor(status), fill = sex))

Here are the charts.

enter image description here

Now I want to add the values (numbers and percentages) into the bars body.

geom_text () will do. I googled some references and tried different combinations for the geom_text (x, y, label) like xxx. They are not shown properly.

Wrong code:

geom_text(aes(as.factor(status), y = sex, label = sex))

How can I do this?


Solution

  • I found it easiest to summarise the data outside of ggplot and then it became relatively simple.

    library(tidyverse)
    
    data2 <- data %>%
      group_by(sex, status) %>%
      summarise (n = n()) %>%
      mutate(percent = n / sum(n) * 100)
    
    ggplot(data2, aes(sex, percent, group = status)) +
      geom_col(aes(fill = status)) +
      geom_text(aes(label = round(percent,1)), position = position_stack(vjust = 
      0.5))
    

    enter image description here

    ggplot(data2, aes(status, n, group = sex)) +
      geom_col(aes(fill = sex)) +
      geom_text(aes(label = n), position = position_stack(vjust = 0.5))
    

    enter image description here