Markm0705
Markm0705

Reputation: 1440

R ggplot2 fit smoothed line to all data while having groups

The following code makes each group have a different colored point on a scatterplot.

df = mtcars

df$cyl = factor(df$cyl)

ggplot(df, aes(x = mpg, y = disp, colour = cyl, group = cyl)) + 
  geom_point(size = 5) + 
  geom_smooth()

However, when I add a smooth line - a smoothed line is created for each group. How do I add a smoothed line for all the data, while retaining the different group colors?

Data coloured by group

Upvotes: 2

Views: 987

Answers (1)

Kra.P
Kra.P

Reputation: 15143

change location of colour and group will do

    df %>%
    ggplot( aes(x = mpg, y = disp)) + 
      geom_point(size = 5, aes(colour = cyl, group = cyl)) + 
      geom_smooth()

enter image description here

Upvotes: 3

Related Questions