library(tidyverse)
library(gapminder)
library(ggpmisc)
library(ggsci)
library(grid)
df <- read_tsv("data.xls") %>% filter(!continent %in% c("Oceania","Americas"),year >=1982)
❝在这个案例中我们介绍使用「stat_quant_eq」函数自动添加拟合曲线的R值与P值❞
df %>% ggplot(aes(gdpPercap,lifeExp,color=continent))+
geom_point(size=2.5,aes(color=continent))+
geom_smooth(aes(color=continent),method = 'lm', se = TRUE, show.legend=FALSE)+
facet_wrap(.~year,scales="free_x",nrow=2,ncol=3)+
scale_color_npg()+
stat_poly_eq(method = 'lm',
aes(label=paste(after_stat(rr.label),
after_stat(p.value.label),sep = "*\", \"*")),
size=3)+
labs(x=NULL,y=NULL)+
theme_bw()+
theme(axis.text=element_text(colour='black',size=9),
legend.position = c(0.94,0.1),
legend.background = element_blank(),
legend.key = element_blank(),
legend.title = element_blank())
❝可以看到使用「ggpmisc::stat_poly_eq」函数很轻松的添加上了R值与P值,
但是实际中也许会存函数无法自动添加的情况
,那么就需要使用代码自定义去添加,如果图表只有一个那样操作很是轻松,但若是图表采用分面的形式绘制那么就需要自定义函数来添加文本 ❞
annotation_custom2 <- function (grob, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf, data)
{
layer(data = data, stat = StatIdentity, position = PositionIdentity,
geom = ggplot2:::GeomCustomAnn,
inherit.aes = TRUE, params = list(grob = grob,
xmin = xmin, xmax = xmax,
ymin = ymin, ymax = ymax))
}
grob1 <- grobTree(textGrob(expression(paste(italic(R^2),"=0.25, ",italic(p),"<0.001")),
x=0.1,y=0.95, hjust=0,gp=gpar(col="#DC0000FF", fontsize=10)))
grob2 <- grobTree(textGrob(expression(paste(italic(R^2),"=0.29, ",italic(p),"<0.001")),
x=0.1, y=0.88, hjust=0,gp=gpar(col="#4DBBD5FF", fontsize=10)))
grob3 <- grobTree(textGrob(expression(paste(italic(R^2),"=0.51, ",italic(p),"<0.001")),
x=0.1, y=0.82, hjust=0,gp=gpar(col="#00A087FF", fontsize=10)))
df %>% ggplot(aes(gdpPercap,lifeExp,color=continent))+
geom_point(size=2.5,aes(color=continent))+
geom_smooth(aes(color=continent),method = 'lm', se = TRUE, show.legend=FALSE)+
facet_wrap(.~year,scales="free_x",nrow=2,ncol=3)+
scale_color_npg()+
labs(x=NULL,y=NULL)+
theme_bw()+
theme(axis.text=element_text(colour='black',size=9),
legend.position = c(0.94,0.1),
legend.background = element_blank(),
legend.key = element_blank(),
legend.title = element_blank())+
annotation_custom2(grob1,data=df %>% filter(year==1982))+
annotation_custom2(grob2,data=df %>% filter(year==1982))+
annotation_custom2(grob3,data=df %>% filter(year==1982))