cmirian
cmirian

Reputation: 2253

ggplot: geom_text not printing above geom_col

I have seen numerous threads on how to automatically print a text item above bars. However, I cannot figure out why this is not working.

I have

enter image description here

With

p %>% 
  as_tibble() %>% 
  mutate(nystudie=as.character(nystudie),
         n.stage=as.factor(n.stage)) %>% 
  bind_rows(., mutate(., nystudie="all")) %>% 
  count(nystudie, n.stage) 

As

# A tibble: 13 x 3
   nystudie n.stage     n
   <chr>    <fct>   <int>
 1 A        0           4
 2 A        2           4
 3 A        3           1
 4 all      0          22

I would like n to print as text above each n.stage per nystudie.

So this gives the bar plot

  ggplot(aes(nystudie, n, color = n.stage, fill= n.stage, label=n)) +
  geom_col(position = position_dodge2(preserve = "single", padding = 0.1))

But adding

+ geom_text(vjust=0)

Yields an error:

mapping must be created by aes()

Why is that and how can I make geom_text print the aes(label=n)?

p <- structure(list(nystudie = c("B", "B", "B", "B", "B", "B", "B", 
"B", "B", "B", "B", "B", "A", "A", "B", "B", "B", "B", "B", "B", 
"B", "B", "A", "B", "B", "A", "B", "A", "A", "A", "B", "B", "B", 
"B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", "B", 
"B", "B", "B", "B"), n.stage = structure(c(3L, 5L, 1L, 1L, 1L, 
1L, 5L, 4L, 3L, 2L, 3L, 4L, 1L, 3L, 3L, 1L, 3L, 1L, 2L, 2L, 1L, 
4L, 2L, 1L, 2L, 4L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 4L, 1L, 2L, 1L, 
4L, 4L, 1L, 1L, 5L, 1L, 1L, 2L, 4L, 1L, 4L, 1L, 2L), .Label = c("0", 
"1", "2", "3", "4"), class = "factor")), row.names = c(NA, -50L
), class = "data.frame")

Upvotes: 0

Views: 167

Answers (1)

Duck
Duck

Reputation: 39595

Maybe you are looking for this:

library(tidyverse)
#Data and plot
p %>% 
  as_tibble() %>% 
  mutate(nystudie=as.character(nystudie),
         n.stage=as.factor(n.stage)) %>% 
  bind_rows(., mutate(., nystudie="all")) %>% 
  count(nystudie, n.stage) %>%
  ggplot(aes(nystudie, n, color = n.stage, fill= n.stage, label=n)) +
  geom_col(position = position_dodge2(preserve = "single", padding = 0.1))+
  geom_text(aes(label=n),position = position_dodge2(0.9),vjust=-0.5)

Output:

enter image description here

Upvotes: 3

Related Questions