Search code examples
rggplot2graphdata-visualization

How do I make ggplot2 trendlines, one dashed and another a solid line?


I'd like each trendline on this graph to have a different shape. For example, the "boys" trendline would be dashed, and the "girls" trendline would be a solid line. I am using the ggplot2 library in R. Here is my code.

dr <- ggplot(Tempdata, 
            aes(x = Tempdata$EffortfulControl,
                y = Tempdata$sqrt_Percent.5, 
                color = Tempdata$Sex1M, 
                shape = Tempdata$Sex1M)) + 
geom_point(aes(shape = Tempdata$Sex1M, 
               color = Tempdata$Sex1M), 
           show.legend = FALSE) + 
scale_shape_manual(values=c(16,17))+ 
geom_smooth(method=lm,se=FALSE,fullrange=TRUE) + 
labs(x = "xaxis label",
     y = "yaxis label", 
     fill = "") +
xlim(3,7) +
ylim(0,10)

dr +  
scale_colour_grey(start = 0.0, 
                  end = .7 , 
                  guide_legend(title = "")) + 
theme_classic() 

Updated code after @nebroth 's suggestions

dr <- ggplot(Tempdata, 
       aes(x=Tempdata$EffortfulControl, 
           y=Tempdata$sqrt_Percent.5, 
           color=Tempdata$Sex1M, 
           shape=Tempdata$Sex1M, 
           linetype=Tempdata$Sex1M)) + geom_point(aes(shape=Tempdata$Sex1M, 
               color=Tempdata$Sex1M), 
           show.legend = FALSE) + 
scale_shape_manual(values=c(16,17))+ geom_smooth(method=lm,se=FALSE,fullrange=TRUE) + 
labs(x="xaxislabel", 
     y = "yaxis label", fill= "") + 
xlim(3,7) + 
ylim(0,10)

dr +  
scale_colour_grey(start = 0.0, 
                  end = 0.4, 
                  guide_legend(title = "")) + 
theme_classic()  


Solution

  • First the answer to your question: You can use the linetype parameter in ggplot with the grouping specified: ggplot(data, aes(x=x, y=y, color = z, linetype = z) If alternative data is specified in aes of geom_smooth, it can also be specified within aes.

    A few more tips: In general you don't need to specify your object again within aes, you can just give the colname (e.g. ggplot(Tempdata, aes(x=EffortfulControl, y=sqrt_Percent.5, color=Sex1M, shape=Sex1M)) ) and putting linebreaks between the different layers of your plot helps with readability.