Sacha Epskamp
Sacha Epskamp

Reputation: 47541

separate legend geom_smooth in ggplot2

I want to make a plot very similar to this one:

library(ggplot2)

ggplot(data=mtcars, aes(x = wt,y =  mpg, colour = factor(cyl)))  + 
  geom_line() + geom_smooth(method = "lm", se=FALSE, lty = 2)

However, I specifically want a different entry in the legend for the dashed lines (linear trend) and the solid lines (data). This seems very trivial but for some reason I haven't been able to figure this out.

Upvotes: 2

Views: 2980

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98429

If you need to show 6 different levels in one legend that combines linetypes and colors, then one solution would be to make new data frame that contains original mpg values and predicted values by linear model.

Make new data frame mtcars2 where mgp is replaced with predicted values.

library(plyr)
mtcars2<-ddply(mtcars,.(cyl),mutate,mpg=predict(lm(mpg~wt)))

Add new column to mtcars and new data frame to show real and predicted data

mtcars$type<-"real"
mtcars2$type<-"pred"

Combine both data frames.

mtcars.new<-rbind(mtcars,mtcars2)

Now plot data using combined data frame and for color= and lty= use interaction between cyl and type. With scale_color_manual() and scale_linetype_manual() change values of colors and linetypes.

ggplot(mtcars.new,aes(x=wt,y=mpg,color=interaction(type,factor(cyl)),
              lty=interaction(type,factor(cyl))))+
  geom_line()+
  scale_color_manual("Legend",values=c("red","red",
                            "green","green","blue","blue"))+
  scale_linetype_manual("Legend",values=c(2,1,2,1,2,1))

enter image description here

Upvotes: 3

Related Questions