geom_text ggplot2 code example

Example 1: ggplot2 geom_text reorder

library(dplyr)
library(ggplot2)

# some toy data
data <- tibble(Category = c("Baseball",
                            "Basketball",
                            "Football",
                            "Hockey"),
               n = c(45,10,25,20)) 

# fill is provided to the initial ggplot call - labels are in correct order
ggplot(data, aes (x="", y = n, fill = Category)) +
  geom_bar(width = 1, stat = "identity") +
  geom_text(aes(label = paste(n, "%")),
            position = position_stack(vjust = 0.5))

Example 2: ggplot2 geom_text reorder

library(dplyr)
library(ggplot2)

# some toy data
data <- tibble(Category = c("Baseball",
                            "Basketball",
                            "Football",
                            "Hockey"),
               n = c(45,10,25,20)) 

  # fill is provided to the initial ggplot call - labels are in correct order
  ggplot(data, aes (x="", y = n, fill = Category)) +
    geom_bar(width = 1, stat = "identity") +
    geom_text(aes(label = paste(n, "%")),
            position = position_stack(vjust = 0.5))

   # fill is provided to geom_bar - labels are in reverse order
  ggplot(data, aes (x="", y = n)) +
    geom_bar(aes(fill = Category), width = 1, stat = "identity") +
    geom_text(aes(label = paste(n, "%")),
              position = position_stack(vjust = 0.5))

  # fill is provided to aes in geom_text - yields warning, but labels are in correct order
  ggplot(data, aes (x="", y = n)) +
  geom_bar(aes(fill = Category), width = 1, stat = "identity") +
  geom_text(aes(fill = Category, label = paste(n, "%")),
          position = position_stack(vjust = 0.5))
  #> Warning: Ignoring unknown aesthetics: fill

  # fill variable is provided to group in geom_text - labels are in correct order
  ggplot(data, aes (x="", y = n)) +
    geom_bar(aes(fill = Category), width = 1, stat = "identity") +
    geom_text(aes(label = paste(n, "%"), group = Category),
              position = position_stack(vjust = 0.5))

Tags:

R Example