Search code examples
rplotggplot2legenddensity-plot

Change label keys and title on a density curve plot with ggplot2


I have a density plot with this code:

p <- ggplot(data=paddling, aes(frequency, color=type, fill=type))
p <- p + geom_density(alpha=0.2)
p <- p + scale_x_continuous(limits=c(0, 1000),name='Frequency (Hz)')

enter image description here

I would like to change the legend keys and legend title. I tried using:

 p <- p + scale_fill_discrete(name='Paddling type',labels=c("Hands only", "Hands and feet"))

But it just added another legend on top of the other one:

enter image description here

Any help would be greatly appreciated! Thank you!!


Solution

  • What you were doing was halfway there. As you have two aestethics in use (fill and color), both of these need a legend. So, if you change legend title and labels for fill, the legend for color doesn't change and gets plotted as is. As such, the solution is to add a 'scale_color_discrete':

    #generate data
    
    set.seed(123)
    n=1000
    paddling <- data.frame(frequency=runif(n,0,n),
                           type=sample(c("hand_only","with_feet"),n,T))
    
    
    #plot 
    
    p <- ggplot(data=paddling, aes(frequency, color=type, fill=type)) +
      geom_density(alpha=0.2)+
      scale_x_continuous(limits=c(0, 1000),name='Frequency (Hz)') +
      scale_fill_discrete(name='Paddling type',labels=c("Hands only", "Hands and feet"))+
      scale_color_discrete(name='Paddling type',labels=c("Hands only", "Hands and feet"))
    
    p
    

    enter image description here

    This can be a bit cumbersome if you have a lot of mappings, levels. This is another approach: change the data (both column name and factor levels)

    #note the backticks needed for space
    paddling$`Paddling type` <- paddling$type
    levels(paddling$`Paddling type`) 
    levels(paddling$`Paddling type`) <- c("Hands only","Hands and feet")
    
    
    
    p2 <- p <- ggplot(data=paddling, aes(frequency, color=`Paddling type`, fill=`Paddling type`)) +
      geom_density(alpha=0.2)+
      scale_x_continuous(limits=c(0, 1000),name='Frequency (Hz)')