Search code examples
rggplot2density-plot

Density distribution plot with colour and linetype in one legend


I plotted density distributions of stomach pH in Fed and Fasted states: enter image description here using the following code:

plotobj <- NULL
plotobj <-  ggplot(dfall)
plotobj <- plotobj + geom_density(aes(x=pH, y=..density..,colour=FED,linetype=FED),lwd=0.6)
plotobj <- plotobj + scale_x_continuous(name="Stomach pH\n", breaks=(seq(1,7,1))) 
plotobj <- plotobj + scale_y_continuous(name="Distribution density\n") 
plotobj <- plotobj + scale_colour_brewer(name="Fed status", palette="Set1")  
plotobj

I wanted to use different linetype and colour as apprears in the figure.

Question: Instead of having two legends as appears in the figure, is there a way I can modify the code so the color and linetype appear in one legend?


Solution

  • The scales need to have the same names.

    You can either change scale_colour_brewer(name="Fed status", palette="Set1") to scale_colour_brewer(name="FED", palette="Set1").

    or you can add this to what you have

    plotobj + scale_linetype_manual(name = "Fed Status", values = c("solid", "dashed"))