Skip to content

geom_smooth behaves like geom_path #2028

@izahn

Description

@izahn

I noticed that geom_smooth behaves like geom_path rather than geom_line. For example,

library(ggplot2)

ggplot(transform(mtcars, 
                 pred.mpg = predict(lm(mpg ~ poly(hp, 2), 
                                       data = mtcars), 
                                    interval = "confidence"))) + 
  geom_smooth(aes(x = hp,
                  y = pred.mpg.fit, 
                  ymin = pred.mpg.lwr, 
                  ymax = pred.mpg.upr), 
              stat = "identity")

produces
smooth_example

Whereas ordering by the x-axis variable produces the desired result:

ggplot(transform(mtcars, 
                 pred.mpg = predict(lm(mpg ~ poly(hp, 2), 
                                       data = mtcars), 
                                    interval = "confidence"))[order(mtcars$hp), ]) + 
  geom_smooth(aes(x = hp,
                  y = pred.mpg.fit, 
                  ymin = pred.mpg.lwr, 
                  ymax = pred.mpg.upr), 
              stat = "identity")

smooth_example2

I looked at the geom_smooth code, but I don't understand why it behaves this way. It looks like GeomSmooth calls GeomLine, and GeomLine does

  setup_data = function(data, params) {
    data[order(data$PANEL, data$group, data$x), ]
  }

so I would have thought ordering the data myself would make no difference.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions