在R中绘制回归输出时指定不同组的端点

问题描述 投票:2回答:2
我希望能为我的硕士学位论文提供一些回归输出方面的帮助。我正在评估大象对木质植被的影响,尤其是与人工水坑有关的影响。除了随着距水坑距离的增加而普遍减少外,所涉及的两种植被类型之间的影响也大不相同。

我想出了一种使用visreg绘制此图的令人满意的方法。在下面显示的模型输出中,到水坑的距离和蔬菜类型都说明了损坏,因此我尝试同时显示两者。但是,问题在于,我只有距离红色植被类型最远的水坑(x轴)距离有样本。如您所见,蓝色蔬菜类型的回归线超出了该植被类型的最后一点。无论如何,我可以让蓝线停在距水坑的距离(x轴值)比红线更短的距离处来避免这种情况吗?

请参见模型代码,并在visreg图下方绘制图。

Damage to vegetation (y axis) against distance to waterhole (currently scaled, hence the funny units). The two colours correspond to the two vegetation types

样本数据和代码

> dput(vegdata[21:52, c(4,7,33)]) structure(list(distance = c(207L, 202L, 501L, 502L, 1001L, 1004L, 2010L, 1997L, 4003L, 3998L, 202L, 194L, 499L, 494L, 1004L, 1000L, 2008L, 1993L, 4008L, 3998L, 493L, 992L, 1941L, 2525L, 485L, 978L, 1941L, 3024L, 495L, 978L, 1977L, 2952L), vegtype = structure(c(1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("teak", "term"), class = "factor"), toedl = c(35.48031025, 47.30482718, 25.16709533, 22.29360164, 17.6546533, 12.81605101, 20.34136734, 18.45809334, 11.3578081, 3.490830751, 60.54870317, 44.9863128, 18.81010698, 20.4777188, 30.36994386, 18.7417214, 21.52247156, 18.29685939, 30.26217664, 8.945486104, 43.95749178, 43.54799495, 44.42693993, 50.06207783, 48.05538594, 35.31220933, 52.37339094, 40.51569938, 41.45677007, 58.86629306, 37.80203313, 46.35633342 )), row.names = 21:52, class = "data.frame") m1<-lm(toedl~vegtype+distance, data=vegdata) summary(m1) library(visreg) visreg(oedl6, 'sexactd', by='vegtype',overlay=TRUE, gg=TRUE, points=list(size=2.5), ylab='% old elephant damage', xlab='distance from waterhole')

r regression linear-regression ggplot2
2个回答
3
投票
library(ggplot2) library(visreg) # Create reproducible data example allData <- data.frame(vegtype = rep(c("t1", "t2"), each = 10), oedl = c(seq(from = 35, to = 20, length.out = 10), seq(from = 20, to = 5, length.out = 10)), sexactd = c(seq(from = -1, to = 1, length.out = 10), seq(from = -1, to = 2, length.out = 10))) # Make linear model oedl6 <- lm(formula = oedl ~ sexactd + vegtype, data = allData) # Predict the data using the linear model odelPred <- cbind(allData, predict(oedl6, interval = 'confidence')) ggplot(odelPred, aes(sexactd, oedl, color = vegtype, fill = vegtype)) + geom_point() + geom_line(aes(sexactd, fit)) + geom_ribbon(aes(ymin = lwr, ymax = upr), alpha = 0.3)

0
投票
library(tidyverse) ggplot(vegdata, aes(toedl, distance, color = vegtype)) + geom_point() + geom_smooth(method = 'lm')

“”

reprex package(v0.3.0)在2019-12-13创建
© www.soinside.com 2019 - 2024. All rights reserved.