1
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

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
wwins
  • 13
  • 4
  • please include a sample of your data to make this question reproducible – morgan121 Dec 06 '19 at 01:42
  • I may not understand what you're after, but will `position = 'fill'` do the trick? `geom_bar(aes(fill = success), position = 'fill')` – AHart Dec 06 '19 at 03:14
  • @AHart, no that justifies the chart to 100% of the chart area. My goal is to have percentage labels hovering over the respective colors of each individual bar. – wwins Dec 06 '19 at 03:35

2 Answers2

2

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

AHart
  • 448
  • 3
  • 10
2

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

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213