2

I have a data frame with 10 values in each of the 5 kinds and have 2 types.

df <- data.frame(x2=rnorm(100),y2=rnorm(100), type = c(rep("type a", 50), rep("type b", 50)), kind = rep(LETTERS[1:5],10))

I want to print the labels of percent of values in each quadrants. My current code is:

ggplot(df, aes(x2, y2)) + geom_point() +
  geom_vline(xintercept = 0) +
  geom_hline(yintercept = 0) +
  geom_text(data = df, aes(x2, y2, label = "")) +
  facet_grid(type~kind)

Current output: enter image description here

Expected output (for example I showed percentage of kind A and B of type a, i want to plot percent values for all kinds and types): enter image description here

Any suggestion would be great. Thanks!

Rashedul Islam
  • 879
  • 1
  • 10
  • 23

1 Answers1

6

You probably need to calculate the proportions outside ggplot2,

library(dplyr)
numbers <- df %>% group_by(type,kind) %>% mutate(cases = n()) %>% 
  add_count(x2>0,y2>0) %>% mutate(label=paste(round(n/cases*100),"%"), 
                                  x = ifelse(`x2 > 0`, Inf, -Inf), 
                                  y = ifelse(`y2 > 0`, Inf, -Inf), 
                                  hjust = ifelse(`x2 > 0`, 1, 0), 
                                  vjust = ifelse(`y2 > 0`, 1, 0))

ggplot(df, aes(x2, y2)) + geom_point() +
  geom_vline(xintercept = 0) +
  geom_hline(yintercept = 0) +
  facet_grid(type~kind) +
  geom_label(data=numbers, aes(label = label, x=x, y=y, vjust=vjust, hjust = hjust))
baptiste
  • 75,767
  • 19
  • 198
  • 294