我试图通过geom_segment
在地块中添加参考线。
简化示例:
tryCatch({
spaghetti_smooth_ref = qplot(age,T_self, data=sest,geom="blank") +
geom_smooth(method='lm',alpha=0.1, colour = "black") +
geom_segment(aes(x = 16, xend = 45,y = coef(us_ref)["(Intercept)"], yend = coef(us_ref)["(Intercept)"] + coef(us_ref)["age"] * 45), linetype = "solid", colour = "#5e8fb0", alpha = 0.5, size = 0.1) +
facet_wrap(~ country)+
scale_linetype_discrete()
}, error = function(e){warning(e)})
如下所示,geom_smooth()
的呈现速度比geom_segment()
更为流畅。
我该如何改进?在Mac上的Rstudio中查看并以PDF格式呈现时,情况相同。我还使用原始数据和geom_smooth()
绘制了完全相同的斜率,一旦使用geom_segment()
,它们仍然不同。
答案 0 :(得分:1)
尽管这个问题已有5年历史了,但我最近遇到了同样的问题并能够解决。希望我的回答可以帮助其他经历类似的事情。
您可以创建一个附加的数据框,其中包含x轴和y轴的最小值和最大值。然后使用geom_line()
添加所需的行。
data_df = data.frame(Gender = rep(c("Female", "Male"),each = 10),
Height = c(63.26153, 61.56266, 64.80651, 63.29383, 66.44624, 67.12988, 64.13034, 66.64640, 64.74866, 73.08489,
62.01556, 72.80084, 69.28989, 67.56494, 68.01175, 70.99855, 68.19854, 71.81611, 73.08489, 70.95103),
Weight = c(126.4268, 131.7959, 156.0956, 159.8213, 135.6089, 146.6043, 121.2926, 156.4250, 133.5414, 158.2851,
117.6670, 206.8282, 179.5619, 156.1813, 175.0151, 195.9590, 176.4568, 205.9251, 230.6788, 196.6997))
model = lm(Weight~Height, data = data_df)
lines_df = data.frame(Height = c(min(data_df$Height), max(data_df$Height)),
Weight = c(coef(model)["(Intercept)"] + coef(model)["Height"] * min(data_df$Height),
coef(model)["(Intercept)"] + coef(model)["Height"] * max(data_df$Height)))
ggplot(data_df, aes(x = Height, y = Weight)) +
geom_smooth(method = "lm", alpha = 0.1, colour = "black", size = 0.5) +
geom_line(aes(y = Weight), data = lines_df, linetype = "solid", colour = "#5e8fb0", size = 0.5)+
facet_grid(.~Gender)
答案 1 :(得分:0)
你能不能用abline
定义自己的参考线? E.g。
+ geom_abline(intercept = 48.5, slope = 0.1)