Printing correlation data in the same plot on the edges

I have a ggplot2 facet scatter ggplot2 and would like to print a summary of linear regression statistics on each face, as was done here and. Unlike these examples, I use scales="free" , and the data ranges in each face have completely different values, but I would like the summary statistics to be displayed in the same relative position in each face (for example, in the upper right corner or anywhere else). How can I tell geom_text or annotate that the label should be displayed in the same position relative to the panel?

Where am I now:

 # Fake data set.seed(2112) x <- c(1:10, 6:15) y <- x + c(runif(10), runif(10)*10) l <- gl(2, 10) d <- data.frame(x=x, y=y, l=l) # Calculate a summary statistic (here, the r-squared) in a separate data frame r_df <- ddply(d, .(l), summarise, rsq=round(summary(lm(y~x))$r.squared, 2)) # Use geom_text and a separate data frame to print the summary statistic ggplot(d, aes(x=x, y=y)) + geom_text(data=r_df, aes(x=8, y=8, label=paste("rsq=", rsq)))+ geom_point() + facet_wrap(~l, scales="free") 

enter image description here

I would like, instead, ggplot automatically position the text at the same relative position in each face.

+6
source share
1 answer

If you want to position them relative to the corners, you can achieve this by specifying the x or y position as Inf or -Inf :

 ggplot(d, aes(x=x, y=y)) + geom_text(data=r_df, aes(label=paste("rsq=", rsq)), x=-Inf, y=Inf, hjust=-0.2, vjust=1.2)+ geom_point() + facet_wrap(~l, scales="free") 

enter image description here

I also adjusted hjust and vjust so that the label was not in the exact corner of the graph, pushing away a bit from it.

+15
source

Source: https://habr.com/ru/post/952532/


All Articles