Adding labels to individual % inside geom_bar() us

2020-04-18 08:44发布

bgraph <- ggplot(data = data, aes(x = location)) +
  geom_bar(aes(fill = success))

success is a percentage calculated as a factor of 4 categories with the varying 4 outcomes of the data set. I could separately calculate them easily, but as the ggplot is currently constituted, they are generated by the geom_bar(aes(fill=success)).

data <- as.data.frame(c(1,1,1,1,1,1,2,2,3,3,3,3,4,4,4,4,4,4,
                        4,4,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7))
data[["success"]] <- c("a","b","c","c","d","d","a","b","b","b","c","d",
                       "a","b","b","b","c","c","c","d","a","b","c","d",
                       "a","b","c","c","d","d","a","b","b","c","d")
names(data) <- c("location","success")
bgraph <- ggplot(data = data, aes(x = location)) +
  geom_bar(aes(fill = success))
bgraph

How do I get labels over the individual percentages? More specifically, I wanted 4 individual percentages for each bar. One for yellow, light orange, orange, and red, respectively. %'s all add up to 1.

Bar Graph

标签: r ggplot2
2条回答
Emotional °昔
2楼-- · 2020-04-18 09:15

How about creating a summary frame with the relative frequencies within location and then using that with geom_col() and geom_text()?

# Create summary stats
tots <-
  data %>%
  group_by(location,success) %>%
  summarise(
    n = n()
  ) %>%
  mutate(
    rel = round(100*n/sum(n)),
  )

# Plot
ggplot(data = tots, aes(x = location, y = n)) +
  geom_col(aes(fill = fct_rev(success))) + # could only get it with this reversed
  geom_text(aes(label = rel), position = position_stack(vjust = 0.5))

OUTPUT: Bar plot with centered labels

查看更多
forever°为你锁心
3楼-- · 2020-04-18 09:16

Maybe there is a way to do this in ggplot directly but with some pre-processing in dplyr, you'll be able to achieve your desired output.

library(dplyr)
library(ggplot2)

data %>%
  count(location, success) %>%
  group_by(location) %>%
  mutate(n = n/sum(n) * 100) %>%
  ggplot() + aes(x = location, n, fill = success,label = paste0(round(n, 2), "%")) +
  geom_bar(stat = "identity") +
  geom_text(position=position_stack(vjust=0.5))

enter image description here

查看更多
登录 后发表回答