本文介绍了将回归直线添加到R中的qplot的facet_grid中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 qplot(date) 我试图给这个facet_grid添加一条回归线,但我似乎遇到了问题。 ,data = ua,geom =bar, weight = count, ylab =新用户计数, xlab ='Date', main ='新用户('greengreen'), fill = I('gray'))+ facet_grid(un_region_ role,scales ='free',按类型划分的最后3个月', color = I space ='free_y')+ opts(axis.text.x = theme_text(angle = 45,size = 5)) 下面是我正在使用的数据的一个示例,请注意计数需要相加,这就是为什么我使用weight = count,并不确定是否有更好的方法。 p> 日期角色名称un_region un_subregion us_state计数 1 2012-06-21 ENTREPRENEUR澳大利亚大洋洲澳大利亚d新西兰2 2 2012-06-21 ENTREPRENEUR比利时欧洲西欧1 谢谢。解决方案我不知道你在绘制斜率,因为你似乎在使用条形图。有三种方法可以做到,我将说明两种。如果你有实际的xy数据,并且你想通过方面来拟合单独的回归线,只需使用 stat_smooth(method =lm)。这里有一些代码: library(ggplot2)x y< - (c(rep(A,50),rep(B,50))) f2< - as.factor(rep(c(rep(C,25),rep(D,25)),2)) df df $ f1 df $ f2 ggplot(df,aes(x = x,y = y))+ geom_point()+ facet_grid(f1〜f2)+ stat_smooth(method =lm,se = FALSE) : 或者您可以使用 geom_abline()命令设置您自己的截距和斜率。下面是一个使用菱形数据集覆盖在条形图上的示例,也许您在寻找什么。 你可以看到一个只有散布图的例子,其中有 ggplot(df,aes(x = x,y = y))+ geom_point()+ facet_grid(f1〜f2)+ geom_abline(截距= 0,slope = 1) p> I am trying to add a regression line to this facet_grid, but i seem to be having problems. qplot(date, data=ua, geom="bar", weight=count, ylab="New User Count", xlab='Date', main='New Users by Type Last 3 Months', colour=I('lightgreen'), fill=I('grey')) + facet_grid(un_region~role, scales='free', space='free_y') + opts(axis.text.x =theme_text(angle=45, size=5))Here's a sample of the data i am working with, note that the counts need to be summed, this is why i am using weight=count, not sure if there is a better way. date role name un_region un_subregion us_state count1 2012-06-21 ENTREPRENEUR Australia Oceania Australia and New Zealand 22 2012-06-21 ENTREPRENEUR Belgium Europe Western Europe 1Thanks. 解决方案 I'm not sure what you're drawing the slope of since it seems that you're using a bar plot. There are three ways you can do it, I'll illustrate two. If you have actual xy data and you want to fit individual regression lines by facet, just use stat_smooth(method="lm"). Here's some code:library(ggplot2)x <- rnorm(100)y <- + .7*x + rnorm(100)f1 <- as.factor(c(rep("A",50),rep("B",50)))f2 <- as.factor(rep(c(rep("C",25),rep("D",25)),2))df <- data.frame(cbind(x,y))df$f1 <- f1df$f2 <- f2ggplot(df,aes(x=x,y=y))+geom_point()+facet_grid(f1~f2)+stat_smooth(method="lm",se=FALSE)This yields: Or you can use the geom_abline() command to set your own intercept and slope. Here's an example using the diamonds data set overlaid on a bar plot, maybe what you're looking for.You can see an example with just the scatterplots with this snippetggplot(df,aes(x=x,y=y))+geom_point()+facet_grid(f1~f2)+geom_abline(intercept = 0, slope = 1 ) 这篇关于将回归直线添加到R中的qplot的facet_grid中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-11 03:33