[英]ggplot2: add regression equations and R2 and adjust their positions on plot
使用df
和下面的代碼
library(dplyr)
library(ggplot2)
library(devtools)
df <- diamonds %>%
dplyr::filter(cut%in%c("Fair","Ideal")) %>%
dplyr::filter(clarity%in%c("I1" , "SI2" , "SI1" , "VS2" , "VS1", "VVS2")) %>%
dplyr::mutate(new_price = ifelse(cut == "Fair",
price* 0.5,
price * 1.1))
ggplot(df, aes(x= new_price, y= carat, color = cut))+
geom_point(alpha = 0.3)+
facet_wrap(~clarity, scales = "free_y")+
geom_smooth(method = "lm", se = F)
我有這個情節
感謝@ kdauria對這個問題的回答,我將回歸方程和R2添加到如下圖中
source_gist("524eade46135f6348140")
ggplot(df, aes(x= new_price, y= carat, color = cut))+
stat_smooth_func(geom="text",method="lm",hjust=0,parse=TRUE)+
geom_point(alpha = 0.3)+
facet_wrap(~clarity, scales = "free_y")+
geom_smooth(method = "lm", se = F)
現在,我想將回歸方程的位置和R2調整到每個小平面中的特定位置(例如,在每個小平面的右下方,例如0.2 y和0.8 x)。
我試圖通過調整位置vjust
和hjust
,但沒有奏效。
任何建議都將受到高度贊賞。
嘗試stat_poly_eq
從包ggpmisc
:
library(ggpmisc)
formula <- y ~ x
ggplot(df, aes(x= new_price, y= carat, color = cut)) +
geom_point(alpha = 0.3) +
facet_wrap(~clarity, scales = "free_y") +
geom_smooth(method = "lm", formula = formula, se = F) +
stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
label.x.npc = "right", label.y.npc = 0.15,
formula = formula, parse = TRUE, size = 3)
回報
有關控制輸出的其他選項,請參閱?stat_poly_eq
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.