本文介绍了ggplot2:在每个构面上添加回归线方程时,x轴存在问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基于此处的示例在图表上添加回归线方程和R2 ,我很努力在每个方面都包括我的模型的回归线方程.但是,我不知道为什么要更改我的x轴的限制.
Based on the example hereAdding Regression Line Equation and R2 on graph, I am struggling to include the regression line equation for my model in each facet. However, I don't figure why is changing the limits of my x axis.
library(ggplot2)
library(reshape2)
df <- data.frame(year = seq(1979,2010), M02 = runif(32,-4,6),
M06 = runif(32, -2.4, 5.1), M07 = runif(32, -2, 7.1))
df <- melt(df, id = c("year"))
ggplot(data = df, mapping = aes(x = year, y = value)) +
geom_point() +
scale_x_continuous() +
stat_smooth_func(geom = 'text', method = 'lm', hjust = 0, parse = T) +
geom_smooth(method = 'lm', se = T) +
facet_wrap(~ variable) # as you can see, the scale_x_axis goes back to 1800
如果我在x上加上了限制,
If I include on the x the limits,
scale_x_continuous(limits = c(1979,2010))
它不再显示回归系数.我在这里做什么错了?
it does not show the regression coefficient anymore. What am I doing wrong here?
stat_smooth_func此处可用: https://gist.github.com/kdauria/524eade46135f6348140
推荐答案
您可以使用stat_poly_eq函数/user-guide.html#stat_poly_eq"rel =" nofollow noreferrer> ggpmisc
包.
You can use stat_poly_eq
function from the ggpmisc
package.
library(reshape2)
library(ggplot2)
library(ggpmisc)
#> For news about 'ggpmisc', please, see https://www.r4photobiology.info/
#> For on-line documentation see https://docs.r4photobiology.info/ggpmisc/
df <- data.frame(year = seq(1979,2010), M02 = runif(32,-4,6),
M06 = runif(32, -2.4, 5.1), M07 = runif(32, -2, 7.1))
df <- melt(df, id = c("year"))
formula1 <- y ~ x
ggplot(data = df, mapping = aes(x = year, y = value)) +
geom_point() +
scale_x_continuous() +
geom_smooth(method = 'lm', se = TRUE) +
stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~~")),
label.x = "left", label.y = "top",
formula = formula1, parse = TRUE, size = 3) +
facet_wrap(~ variable)
ggplot(data = df, mapping = aes(x = year, y = value)) +
geom_point() +
scale_x_continuous() +
geom_smooth(method = 'lm', se = TRUE) +
stat_poly_eq(aes(label = paste(..eq.label.., sep = "~~~")),
label.x = "left", label.y = 0.15,
eq.with.lhs = "italic(hat(y))~`=`~",
eq.x.rhs = "~italic(x)",
formula = formula1, parse = TRUE, size = 4) +
stat_poly_eq(aes(label = paste(..rr.label.., sep = "~~~")),
label.x = "left", label.y = "bottom",
formula = formula1, parse = TRUE, size = 4) +
facet_wrap(~ variable)
这篇关于ggplot2:在每个构面上添加回归线方程时,x轴存在问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!