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

后端 未结 2 1666
野的像风
野的像风 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条回答
  • 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)
    )
    
    0 讨论(0)
  • 2020-12-29 16:10

    This solution is aimed at plotting 2 curves from 1 data frame. One column data is plotted as line graph against the x-axis (Observation Date) and the other is plotted as Area Graph against the same x-axis(Observation Date). Area Curve will be on secondary y-axis. The Legend plotting and Formatting are also shown in the images attached. Hope you enjoy the solution.

    Data Frame structure will look like as follows/ This is a sample of the whole dataset, I will pick 2 columns, obsdate, revenue, and value:

    This is a sample of the whole dataset, I will pick 2 columns, obsdate, revenue, and value

    I am using Shiny library to host it on a server; if you don't know about shiny you may ignore, this is just the layout~HTML.

    library(xlsx) # Library for Excel import 
    library (ggplot2) # Library for plot
    library(openxlsx) #FOR Running the xlsx file 
    library(shiny) #SERVER UI LIBRARY IN R
    library(lubridate) # For converting the imported dates to Date Format
    
    file <- "C:/Users/Nikhil Asati/Desktop/Office/Bicurve_data.xlsx"
    data1<- read.xlsx( file ,1)
    data1$obsdate <- dmy(data1$obsdate)
    
    ui <- fluidPage(
      sidebarLayout(
        sidebarPanel(),
        mainPanel(
          plotOutput("Plot")
        )
      )
    )
    server <- function(input, output) {
      output$Plot <- renderPlot({
        #plot value
        p <- ggplot(data1, aes(x=obsdate))
            p <- p + geom_line(aes(y=revenue, colour ="revenue"))
        #plot revenue
            p <- p + geom_ribbon(aes(ymin = 0, ymax=value/16, fill = 'value'),  
                                 linetype=1,     
                                 #solid, dashed or other line types
                                 colour="grey70",
                                 #border line color
                                 size=1
                                 # ,show.legend= TRUE
            )
             p <- p + scale_y_continuous(sec.axis = sec_axis(~.*16, name = "value"))
              
             p<- p + scale_colour_manual("", values=c("revenue" = "Grey" ))
             p<- p +scale_fill_manual(name = "", values = c("value" = "green"))
             p<- p +theme(legend.position = "top") 
             p
      })
      
    }
    
    
    shinyApp(ui = ui, server = server) 
    

    Output will be:

    Output Curve

    0 讨论(0)
提交回复
热议问题