Adding a regression line to facet_grid with qplot in R

I am trying to add a regression row to this facet_grid, but I am 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 is an example of the data I'm working with, note that the counts need to be summed, so I use weight = count, not sure if there is a better way.

  date role name un_region un_subregion us_state count 1 2012-06-21 ENTREPRENEUR Australia Oceania Australia and New Zealand 2 2 2012-06-21 ENTREPRENEUR Belgium Europe Western Europe 1 

Thanks.

0
source share
1 answer

I'm not sure that you are drawing a slope, as it seems that you are using a bar. There are three ways to do this, I will illustrate two. If you have actual xy data and want to put separate regression lines on the edge, just use stat_smooth(method="lm") . Here is the 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 <- f1 df$f2 <- f2 ggplot(df,aes(x=x,y=y))+geom_point()+facet_grid(f1~f2)+stat_smooth(method="lm",se=FALSE) 

This gives:

enter image description here

Or you can use the geom_abline() command to set your own interception and tilt. Here's an example of using a diamond dataset superimposed on a bar chart, perhaps what you are looking for.

enter image description here

You can see an example using the diagrams with this fragment ggplot(df,aes(x=x,y=y))+geom_point()+facet_grid(f1~f2)+geom_abline(intercept = 0, slope = 1 )

+3
source

All Articles