I was using the ggpubr
package and the ggpubr::stat_cor
function to get some information about the correlation added to a plot. Here is some simple example code:
library(ggpubr)
set.seed(123)
n <- 1000
x_vec <- runif(n)
y_vec <- 3 + 1.3*x_vec + rnorm(n)
df <- data.frame(x = x_vec, y = y_vec)
ggplot(df, aes(x, y)) +
geom_point() +
stat_cor(p.accuracy = 0.00001)
The resulting plot has a p-value in the top left corner:
I like to have the confidence interval instead, so I made a small PR to ggpubr
to achieve this, (see here).
I made the change to the package, since that was the fastest way I could figure out to achieve the desired result. I am wondering whether there is a simple elegant way to achieve the same results with ggplot
directly, or possibly some other package?
Edit: I am aware of geom_text
, and I want to do this, e.g. when I facet
, such that I use the data defined by the grouping in ggplot
to achieve this, e.g.
df <- data.frame(x = x_vec, y = y_vec, grp = sample(1:4, n, replave=TRUE)
ggplot(df, aes(x, y, group = grp)) +
geom_point() +
facet_wrap(vars(grp)) +
stat_cor(p.accuracy = 0.00001)
Which gives the following: