How to add a legend for two geom layers in one ggplot2 plot?

后端 未结 2 1684
野的像风
野的像风 2020-12-29 15:49

I\'ve got a data frame that looks like this:

glimpse(spottingIntensityByMonth)
# Observations: 27
# Variables: 3
# $ yearMonth  2015-05-01, 2015-         


        
2条回答
  •  Happy的楠姐
    2020-12-29 15:52

    In ggplot, legends are automatically created for mapped aesthetics. You can add such mappings as follows:

    ggplot(data = df, 
           mapping = aes(x = x)) + 
    
      # specify fill for bar / color for line inside aes(); you can use
      # whatever label you wish to appear in the legend
      geom_col(aes(y = y.bar, fill = "bar.label")) +
      geom_line(aes(y = y.line, color = "line.label")) +
    
      xlab("Month of year") + 
      scale_y_continuous(name = "Daily classifications per Spotter") + 
    
      # the labels must match what you specified above
      scale_fill_manual(name = "", values = c("bar.label" = "grey")) +
      scale_color_manual(name = "", values = c("line.label" = "black")) +
    
      theme_bw()
    

    In the above example, I've also moved the data & common aesthetic mapping (x) to ggplot().

    Sample dataset:

    set.seed(7)
    df <- data.frame(
      x = 1:20,
      y.bar = rpois(20, lambda = 5),
      y.line = rpois(20, lambda = 10)
    )
    

提交回复
热议问题