我有一个图,我正在绘制每个变量水平的线性回归以及总样本的线性回归。
library(ggplot2);library(curl)
df<-read.csv(curl("https://raw.githubusercontent.com/megaraptor1/mydata/main/example.csv"))df$group<-as.factor(df$group)
ggplot(df,aes(x,y))+
geom_point(size=2.5,shape=21,aes(fill=group),col="black")+
geom_smooth(formula=y~x,aes(col=group,group=group),method="lm",size=1,se=F)+
geom_smooth(formula=y~x,method="lm",col="black",size=1,fullrange=T,se=F)+
theme_classic()+
theme(legend.position = "none")
我正在尝试使用命令 fullrange=T 扩展黑线(代表所有样本)以跨越整个轴范围。但是,我发现无论我尝试什么,命令 fullrange=T 都无法处理此图。这特别奇怪,因为我没有为图表调用任何限制或设置任何额外的全局因素。
这个问题是我能找到的最接近我当前问题的问题,但它似乎没有描述相同的问题,因为该问题与如何调用图形的限制有关。
这看起来有点笨拙,但允许您将回归线扩展到您为 x 轴选择的任何限制。
论点
fullrange
并没有真正被记录下来很有帮助。如果您查看 http://www.mosaic-web.org/ggformula/reference/gf_smooth.html,“全范围”似乎适用于数据框中用于生成回归线的点。所以在你的情况下你的回归线延伸到“全范围”。只是你对“fullrange”的定义和geom_smooth
使用的不太一样。
library(ggplot2)
library(dplyr)
library(curl)
lm_formula <- lm(formula = y~x, data = df)
f_lm <- function(x){lm_formula$coefficients[1] + lm_formula$coefficients[2] * x}
df_lim <-
data.frame(x = c(0, 5)) %>%
mutate(y = f_lm(x))
ggplot(df,aes(x,y))+
geom_point(size=2.5,shape=21,aes(fill=group),col="black")+
geom_smooth(formula=y~x,aes(col=group,group=group),method="lm",size=1,se=F)+
geom_line(data = df_lim)+
coord_cartesian(xlim = df_lim$x, ylim = df_lim$y, expand = expansion(mult = 0))+
theme_classic()+
theme(legend.position = "none")
数据
df<-read.csv(curl("https://raw.githubusercontent.com/megaraptor1/mydata/main/example.csv"))
df$group<-as.factor(df$group)
由 reprex 包 (v1.0.0) 于 2021-04-05 创建
我有同样的问题。尽管设置了
fullrange = TRUE
,但最佳拟合线仅在数据范围内绘制。
ggplot(data = df, aes(x = diameter, y = height)) +
geom_point(size = 2) +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE) +
labs(x = "Diameter", y = "Height", title = "Tree Height vs. Diameter") +
theme(plot.title = element_text(hjust = 0.5, size = 15, face = 'bold'))
使用
scale_x_continuous()
和 scale_y_continuous()
对我有用(谢谢@markus)。我在geom_smooth()
下面添加了两行代码来解决这个问题。
ggplot(data = df, aes(x = diameter, y = height)) +
geom_point(size = 2) +
geom_smooth(method = lm, se = FALSE, fullrange = TRUE) +
scale_x_continuous(expand = c(0,0), limits=c(5, 32)) + #expand = c(num1,num2) => line of best fit stops being drawn at x = 32 + (32 - 5)*num1 + num2 = 32 + (32 - 5)*0 + 0 = 32
scale_y_continuous(expand = c(0,0), limits=c(7, 25)) + #expand = c(num1,num2) => line of best fit stops being drawn at y = 25 + (25 - 7)*num1 + num2 = 25 + (25 - 7)*0 + 0 = 25
labs(x = "Diameter", y = "Height", title = "Tree Height vs. Diameter") +
theme(plot.title = element_text(hjust = 0.5, size = 15, face = 'bold'))