1

Is it possible to add number of points (as text in top right) inside each plot in R.

Thanks

library(tidyverse)

a <- rnorm(100, mean = 0, sd = 1)
b <- rnorm(100, mean = 0, sd = 1)

p <- tibble(a, b) %>%
  pivot_longer(cols = everything(), names_to = "category", values_to = "values") %>%
  ggplot() + 
  geom_histogram(aes(x = values),
                 bins = 20,
                 color = "black",
                 fill = "blue", 
                 alpha = 0.7) + 
  theme_bw() + 
  facet_grid(category ~ .)

ggsave("sample.png", p)

enter image description here

SiH
  • 1,378
  • 4
  • 18
  • You can use `geom_text`. Please check [here](https://stackoverflow.com/questions/24198896/how-to-get-data-labels-for-a-histogram-in-ggplot2) – akrun Dec 12 '20 at 21:18

1 Answers1

1

Try this:

library(tidyverse)
#Data
a <- rnorm(100, mean = 0, sd = 1)
b <- rnorm(100, mean = 0, sd = 1)
#Plot
tibble(a, b) %>%
  pivot_longer(cols = everything(), names_to = "category", values_to = "values") %>%
  ggplot() + 
  geom_histogram(aes(x = values),
                 bins = 20,
                 color = "black",
                 fill = "blue", 
                 alpha = 0.7) + 
  theme_bw() + 
  geom_text(data=tibble(a, b) %>%
              pivot_longer(cols = everything(),
                           names_to = "category",
                           values_to = "values") %>%
              group_by(category) %>% summarise(N=n()),
            aes(x=0,y=20,label=N))+
  facet_grid(category ~ .)

Output:

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84