Managing legend on ggplot2 plot with multiple graph types

Currently, I have a plot that displays data with geom_density, geom_bar, and geom_line graphs, as is shown in the example below.

I want to display a legend for the plot, where each graph type is a different item in the legend. I can get all three boxes in the legend to appear, however, the colors do not accurately match up to their graph type and the background of each box is filled by the fill color of the bar graph instead of being white.

My aim is to have three "boxes", the first being for the usage_cap which is just a red line (with no red outline on the box as there is now), a second box for prepaid which is just the green line (again no outline on the box), and finally a solid box that represents the bar graphs or usage.

This is the code that I currently have to generate the plot:

  output$usagePlot <- renderPlot({
    df <- data_group()

    pp <- ggplot(data=df, aes(x=date)) +
      geom_bar(stat="identity", aes(y=usage_TB, colour = "Usage"), fill = "skyblue4") +
      geom_line(aes(y=usagecap_GB/1000, colour = "Usage Cap"), size=2) +
      geom_density(stat="identity", aes(y=prepaid_GB/1000, colour = "Prepaid"), fill = "cyan4", alpha =0.3) +
      scale_colour_manual(values=c("black", "#2f5966", "red")) +
      #scale_fill_manual() +
      labs(colour = "Information") +
      
      xlim(input$dates) +
      theme(
        axis.text.x = element_text(size=12),
        axis.text.y = element_text(size=12),
        axis.title.x = element_text(size=17),
        axis.title.y = element_text(size=17),
        legend.position = "bottom",
        #legend.background = element_rect(fill = "blue"),
        legend.key = element_rect(fill = "white", color = NA)
        )

    pp + ylab("Usage (TB)") + xlab("Date")
  })

If anyone has any suggestions on how to handle this, they would be greatly appreciated!

Hi!

To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

Have in mind that you are describing an issue with ggplot2 not related to shiny even if you are using ggplot() inside a shiny app.

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.