繁体   English   中英

ggplot2中的回归线

[英]Regression line in ggplot2

我试图使用ggplot在下面的图中添加回归线,但它一直给我模糊的错误。 我是一个新手,关于这个问题的其他任何问题都没有解决我的问题,所以请不要对已经回答的类似问题感到生气。

library(UsingR,ggplot2); data(galton)  
y <- galton$child  
x <- galton$parent  
freqData <- as.data.frame(table(galton$child, galton$parent))  
names(freqData) <- c("child", "parent", "freq")  
regression <- coef(lm(y~x))  

freqData <- freqData[freqData$freq > 0,]  

g <- ggplot(data=freqData, aes(x = parent, y = child))  
g <- g + scale_size(range = c(2,20), guide = 'none')  
g <- g + geom_point(colour="grey50", aes(size=freq+20,show_guide=FALSE))  
g <- g + geom_point(aes(colour=freq,size=freq))  
g <- g + scale_colour_gradient(low="lightblue",high="darkblue")  

我试过以下命令:

g <- g + geom_smooth(method="lm",se=FALSE)

(它会产生这个错误: geom_smooth: Only one unique x value each group.Maybe you want aes(group = 1)?

g <- g + geom_abline(intercept = 28.942, slope = 0.646,colour = "red",size = 3)

(但我的情节中没有任何内容......)

这是一个data.table-solution(由@ MikeWise提示,用来展示你设计的很酷的情节)

library(UsingR,ggplot2); data(galton)  
library(data.table)

#making data.table object
dat <- galton
setDT(dat)

#getting frequencies    
freqData <- dat[,.(freq=.N),by=.(child,parent)]


g <- ggplot(data=freqData, aes(x = parent, y = child))  
g <- g + scale_size(range = c(2,20), guide = 'none')  
g <- g + geom_point(colour="grey50", aes(size=freq+20,show_guide=FALSE))  
g <- g + geom_point(aes(colour=freq,size=freq))  
g <- g + scale_colour_gradient(low="lightblue",high="darkblue")  
g <- g + geom_smooth(method="lm",se=FALSE)
g

在此输入图像描述

第一种选择

继续使用函数table 。在绘制图表之前,我们使用type.convert将变量parent和child转换为适当的类型。

library(UsingR,ggplot2); data(galton)

# Create data frame
freqData <- data.frame(table(galton$child, galton$parent))
names(freqData) <- c("child", "parent", "freq")  
freqData <- freqData[freqData$freq > 0,] 

# Convert factors to numeric
freqData[] <- lapply(freqData, function(x) type.convert(as.character(x)))

第二种选择

使用函数aggregate ,以防止类型转换。

freqData <- aggregate(galton, by = list(parent = galton$parent, child = galton$child), 
                      FUN = length)
colnames(freqData)[3] <- "freq" 

第三种选择

使用dplyr来避免类型转换。

library(dplyr)
freqData <- galton  %>%  group_by(parent, child) %>% summarise(freq = n())

通过三个选项之一绘制先前创建的数据框。

# Plot data
g <- ggplot(data=freqData, aes(x = parent, y = child))+ 
  scale_size(range = c(2,20), guide = 'none')  +
  geom_point(colour="grey50", aes(size=freq+20,show_guide=FALSE)) +
  geom_point(aes(colour=freq,size=freq)) +
  scale_colour_gradient(low="lightblue",high="darkblue") +
  geom_smooth(method = lm, se = FALSE)
g

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM