简体   繁体   中英

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.

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))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM