7

I have data as below:

numbers <- structure(list(density = c(1L, 4L, 10L, 22L, 55L, 121L, 210L, 
444L), females = c(1L, 3L, 7L, 18L, 22L, 41L, 52L, 79L), males = c(0L, 
1L, 3L, 4L, 33L, 80L, 158L, 365L), maleProp = c(0, 0.25, 0.3, 
0.181818181818182, 0.6, 0.661157024793388, 0.752380952380952, 
0.822072072072072), total = c(1L, 4L, 10L, 22L, 55L, 121L, 210L, 
444L)), .Names = c("density", "females", "males", "maleProp", 
"total"), row.names = c(NA, -8L), class = "data.frame")

I want to have a smooth line with glm method with total as weight. I tried,

ggplot(numbers, aes(density, maleProp)) + geom_point() + 
  stat_smooth(method = "glm", 
              method.args = list(family = "binomial", 
                                 type = "response", 
                                 weights = "total"))

I got error,

Warning message:
Computation failed in `stat_smooth()`:
formal argument "weights" matched by multiple actual arguments 

How can I plot the smooth line in this case?

TheRimalaya
  • 4,232
  • 2
  • 31
  • 37
  • I tried your code and it worked. could it be you have 'total' defined somehow else thus confusing the parser? – Zahiro Mor Mar 29 '16 at 14:15
  • 1
    [Zahiro Mor](http://stackoverflow.com/users/4700149/zahiro-mor):: This may be the older version of ggplot, please update your version of ggplot, you will the the same error. – TheRimalaya Mar 29 '16 at 20:34

2 Answers2

6

If you want to use a glm with the parameters you outlined, you can create a wrapper function as follows:

binomial_smooth <- function(...) {
  geom_smooth(method = "glm", method.args = list(family = "binomial"), ...)
}

Which you can use directly on your ggplot2 object:

ggplot(numbers, aes(density, maleProp)) + geom_point() + binomial_smooth(aes(weight = total))
spsaaibi
  • 452
  • 4
  • 13
4

As an updated answer for ggplot2 version 2.2.1:

ggplot(numbers, aes(x = density, y = maleProp, weight = total)) +
    geom_point() + 
    stat_smooth(method = "glm", 
                method.args = list(family = "binomial"))

Note that you can use weight as an aes() argument.

Richard Erickson
  • 2,568
  • 8
  • 26
  • 39