The code is:
library(gginnards)
library(ggpmisc)
library(ggplot2)
set.seed(4321)
x <- 1:100
y <- rnorm(length(x), mean = 10)
my.data <- data.frame(x, y)
ggplot(my.data, aes(x, y)) +
geom_quadrant_lines(colour = "blue", xintercept = 50, yintercept = 10) +
stat_quadrant_counts(colour = "blue", xintercept = 50, yintercept = 10) +
geom_point() +
scale_y_continuous(expand = expansion(mult = 0.15, add = 0))
I'd like to know how to change the label from n=31, n=27, n=22, n=20 to p=31%, p=27%, p=22%, p=20%.
Also how to move n=27 and n=22 to the left a little bit without changing the position of n=31 and n=20? Thanks!
Like many functions in ggplot extensions, stat_quadrant_counts
is easy to use if you want the default options, but a bit trickier if you want to customize the output. From looking at the docs, you can see the calculated stats that are available to use for calculations inside aes()
in the layer, as long as you wrap them in after_stat
, so we can do something like shown below to obtain percent labels if and only if the total number of observations is 100:
ggplot(my.data, aes(x, y)) +
geom_quadrant_lines(colour = "blue", xintercept = 50, yintercept = 10) +
stat_quadrant_counts(colour = "blue", xintercept = 50, yintercept = 10,
aes(label = paste0("p = ", after_stat(count), "%"),
npcx = ifelse(after_stat(quadrant) > 2,
after_stat(npcx) - 0.1,
after_stat(npcx)))) +
geom_point() +
scale_y_continuous(expand = expansion(mult = 0.15, add = 0))