r - separate legend geom_smooth in ggplot2 -


i want make plot similar 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, want different entry in legend dashed lines (linear trend) , solid lines (data). seems trivial reason haven't been able figure out.

if need show 6 different levels in 1 legend combines linetypes , colors, 1 solution make new data frame contains original mpg values , predicted values linear model.

make new data frame mtcars2 mgp replaced predicted values.

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

add new column mtcars , new data frame show real , predicted data

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

combine both data frames.

mtcars.new<-rbind(mtcars,mtcars2) 

now plot data using combined data frame , color= , lty= use interaction between cyl , type. scale_color_manual() , scale_linetype_manual() change values of colors , 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


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -