Skip to content

Instantly share code, notes, and snippets.

@dgkeyes
Created September 17, 2019 03:14
Show Gist options
  • Save dgkeyes/617baf386a1667b4dee1442b408aae92 to your computer and use it in GitHub Desktop.
Save dgkeyes/617baf386a1667b4dee1442b408aae92 to your computer and use it in GitHub Desktop.
library(tidyverse)
diamonds_summary <- diamonds %>%
count(cut) %>%
mutate(cut = factor(cut, levels = c("Fair",
"Good",
"Very Good",
"Premium",
"Ideal"))) %>%
mutate(cut = fct_rev(cut))
ggplot(diamonds_summary, aes(1, n,
fill = cut)) +
geom_col() +
coord_flip() +
geom_text(aes(label = n),
position = position_stack(vjust = 0.5)) +
guides(fill = guide_legend(reverse = TRUE)) +
theme_void() +
theme(legend.position = "bottom")
@z3tt
Copy link

z3tt commented Sep 17, 2019

How about:

library(tidyverse)

diamonds_summary <- diamonds %>% 
  count(cut) %>% 
  mutate(cut = factor(cut, levels = c("Fair",
                                      "Good",
                                      "Very Good",
                                      "Premium",
                                      "Ideal"))) %>% 
  mutate(cut = fct_rev(cut)) %>% 
 ## to make sure cumsum is the same as stacked bars -> order by level 
 arrange(-as.numeric(cut)) %>%  
  mutate(
    ## cumsum used to determine text label position for intermediate levels
    n_cum = cumsum(n),
    ## I prefer to first assign the horizontal adjustment
    adj = case_when(
      as.numeric(cut) == min(as.numeric(cut)) ~ 0,  ## if on the right -> left-alligned
      as.numeric(cut) == max(as.numeric(cut)) ~ 1,  ## if on the left -> rigth-alligned
      TRUE ~ 0.5   ## if in the middle -> centered
    ),
    ## ... which makes it easier to read when assigning the position of the text:
    pos = case_when(
      adj == 0 ~ n_cum + 250,  ## if on the right -> add some for spacing
      adj == 1 ~ -250,  ## if on the left -> negative value for spacing
      TRUE ~ n_cum - (n / 2)  ## if in the middle -> place in the middle of bar (n / 2)
    )
  )

ggplot(diamonds_summary, aes(1, n,
                             fill = cut)) +
  geom_col() +
  coord_flip() +
  ## no position argument, map y and hjust to `pos` and `adj`:
  geom_text(aes(label = n, y = pos, hjust = adj), vjust = 0.5) +
  guides(fill = guide_legend(reverse = TRUE)) +
  theme_void() +
  theme(legend.position = "bottom")

???

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment