1

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 count
1 2012-06-21 ENTREPRENEUR              Australia   Oceania Australia and New Zealand              2
2 2012-06-21 ENTREPRENEUR                Belgium    Europe            Western Europe              1

Thanks.

joran
  • 169,992
  • 32
  • 429
  • 468
RomainD
  • 97
  • 2
  • 7

1 Answers1

4

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 <- f1
df$f2 <- f2

ggplot(df,aes(x=x,y=y))+geom_point()+facet_grid(f1~f2)+stat_smooth(method="lm",se=FALSE)

This yields:

enter image description here

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.

enter image description here

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

emhart
  • 804
  • 5
  • 9