23

How can I apply geom_smooth() for every group ?

The code below uses facet_wrap(), so plots every group in a separate graph.
I would like to integrate the graph, and get one graph.

ggplot(data = iris, aes(x = Sepal.Length,  y = Petal.Length)) +
  geom_point(aes(color = Species)) +
  geom_smooth(method = "nls", formula = y ~ a * x + b, se = F,
              method.args = list(start = list(a = 0.1, b = 0.1))) +
  facet_wrap(~ Species)
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
ogw
  • 353
  • 1
  • 2
  • 13

2 Answers2

19

You have to put all your variable in ggplot aes():

ggplot(data = iris, aes(x = Sepal.Length,  y = Petal.Length, color = Species)) +
  geom_point() +
  geom_smooth(method = "nls", formula = y ~ a * x + b, se = F,
              method.args = list(start = list(a = 0.1, b = 0.1)))

enter image description here

HubertL
  • 19,246
  • 3
  • 32
  • 51
9

Adding a mapping aes(group=Species) to the geom_smooth() call will do what you want.

Basic plot:

  library(ggplot2); theme_set(theme_bw())
  g0 <- ggplot(data = iris, aes(x = Sepal.Length,  y = Petal.Length)) +
        geom_point(aes(color = Species))

geom_smooth:

  g0 + geom_smooth(aes(group=Species),
              method = "nls", formula = y ~ a * x + b, se = FALSE,
              method.args = list(start = list(a = 0.1, b = 0.1)))

formula is always expressed in terms of x and y, no matter what variables are called in the original data set:

  • the x variable in the formula refers to the variable that is mapped to the x-axis (Sepal.Length)
  • the y variable to the y-axis variable (Petal.Length)

The model is fitted separately to groups in the data (Species).

If you add a colour mapping (for a factor variable) that will have the same effect (groups are implicitly defined according to the intersection of all the mappings used to distinguish geoms), plus the lines will be appropriately coloured.

  g0 + geom_smooth(aes(colour=Species),
              method = "nls", formula = y ~ a * x + b, se = FALSE,
              method.args = list(start = list(a = 0.1, b = 0.1)))

As @HubertL points out, if you want to apply the same aesthetics to all of your geoms, you can just put them in the original ggplot call ...

By the way, I assume that in reality you want to use a more complex nls model - otherwise you could just use geom_smooth(...,method="lm") and save yourself trouble ...

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • 3
    Could you please elaborate on where a & b are being defined? The three variables are x=Sepal.Length, y = Petal.Length,color = Species. However, the formula is y ~ a * x + b. How is it specified that Species is a? – HoneyBuddha May 15 '18 at 18:41