Search code examples
rggplot2legendgeom-bar

The legend disappear in my ggplot graph in R


I'd like to add a legend for these two graphs(geom_line and geom_bar), but i cannot see any legend in the screen according to my code.

I want to make a legend which indicates the geom_bar and geom_line.

Here is my full code.

# PGE Data
Date = seq(as.Date("2021-08-27"), as.Date("2021-09-27"), by="days")
Usage = c(4.3, 5, 7, 3.8, 5.6, 2.6, 4.8, 3.2, 2.6, 5.1,
3.3, 3.9, 2.5, 7.1, 3, 2.2, 6.1, 3.2, 3.2, 3.9,
5.6, 3.4, 3.3, 3.3, 4.4, 5.3, 2.9, 7.1, 3.3, 2.5, 3.1, 4.5)
Weather = c(70, 71, 65, 63, 62, 63, 62, 61, 61, 62,
67, 66, 67, 64, 64, 64, 65, 65, 62, 61,
62, 63, 64, 65, 68, 72, 65, 63, 63, 62, 62, 65)

pge = data.frame(Date, Usage, Weather)
head(pge, n = 10)
odd_weather = pge[seq_len(nrow(pge)) %% 2 == 1, ]
purple_weather = odd_weather[c(1, 5, 6, 7, 8, 10, 12, 13, 14, 15, 16), ]
white_weather = odd_weather[c(2, 3, 4, 9, 11), ]

purple_weather
white_weather
ggplot(data = pge) +
  geom_bar(mapping = aes(x = Date, y = Usage),
           width = 0.8,
           colour = 'steelblue3',
           fill = 'steelblue3',
           stat = "identity",
           show.legend = TRUE) +
  geom_line(mapping = aes(x = Date, y = Weather/15),
            color = 'purple', size = 1.2,
            show.legend = TRUE) +geom_text(data = purple_weather,
            mapping = aes(x = Date, y = Weather/15, label = paste0(Weather,"°", sep = '')),
            nudge_y = 0.4,
            size = 2,
            color ='purple') +
  geom_text(data = white_weather,
            mapping = aes(x = Date, y = Weather/15, label = paste0(Weather,"°", sep = '')),
            nudge_y = 0.4,
            size = 2,
            color ='white') +
  labs(title = bold('<') ~ '  Aug 27, 2021 - Sep 27 2021  ' ~  bold('>')) +
  scale_x_date(
    name = " ", 
    labels = c('Fri\n27', 'Tue\n31', 'Sat\n4', 'Wed\n8', 'Sun\n12', 'Thu\n16', 'Mon\n20', 'Fri\n24'),
    breaks = seq.Date(as.Date("2021-08-27"), as.Date("2021-09-24"), by = "4 days")) +
  scale_y_continuous(
    name = " ",
    limits = c(0, 8),
    breaks = seq(0.0, 8.0, by = 2.0), 
    labels = c('0.0', '2.0', '4.0', '6.0', '8.0 kWh')) +
  annotate("segment", x = median(c(as.Date("2021-08-31"), as.Date("2021-09-01"))),
           xend = median(c(as.Date("2021-08-31"), as.Date("2021-09-01"))),
           y = 0, yend = 8.0, colour = 'gray88', size = 0.5) +
  annotate("rect",
           xmin = median(c(as.Date("2021-08-31"), as.Date("2021-09-01"))),
           xmax = median(as.Date("2021-09-02")),
           ymin = 7.6, ymax = 8.0, alpha = 0.5, colour = 'gray88', fill = 'white') +
  annotate("text",
           x = as.Date("2021-09-01"),
           y = 7.85,
           label = "Sep",
           size = 2.5,
           hjust = 0.2) +
  theme(plot.background = element_rect(fill = 'gray96'),
        panel.background = element_rect(fill = 'gray96'),
        panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank(),
        panel.grid.major.y = element_line(color = 'gray88',
                                          size = 0.3,
                                          linetype = 1),
        panel.grid.minor.y = element_blank(),
        axis.ticks = element_blank(),
        plot.title = element_text(size = 8, color = 'gray30', hjust = 0.5),
        axis.text.x = element_text(vjust = 5, size = 8),
        axis.text.y = element_text(hjust = 0, size = 8),
        legend.direction = "horizontal",
        legend.background = element_blank(),
        legend.box.background = element_rect(linewidth = 1),
        legend.title = element_blank(),
        legend.box = "horizontal",
        legend.position = "bottom")

The result of my code is like below. 1

And I want to make my graph like this one. 2


Solution

  • If you want to map something as legend in ggplot you should add it to the aesthetics. In your case for the bars you should add fill to aes and color from your line. if you want to have the right color you could use scale_*_manual for both. You could use the following code:

    library(ggplot2)
    ggplot() +
      geom_bar(data = pge, aes(x = Date, y = Usage, fill = 'steelblue3'),
               width = 0.8,
               stat = "identity",
               show.legend = TRUE) +
      geom_line(data = pge, aes(x = Date, y = Weather/15, color = 'purple'), size = 1.2) +
      geom_text(data = purple_weather,
                                               aes(x = Date, y = Weather/15, label = paste0(Weather,"°", sep = '')),
                                               nudge_y = 0.4,
                                               size = 2,
                                               color ='purple') +
      geom_text(data = white_weather,
                aes(x = Date, y = Weather/15, label = paste0(Weather,"°", sep = '')),
                nudge_y = 0.4,
                size = 2,
                color ='white') +
      labs(title = bold('<') ~ '  Aug 27, 2021 - Sep 27 2021  ' ~  bold('>')) +
      scale_fill_manual(values = 'steelblue3')+
      scale_color_manual(values = "purple") +
      guides(color=guide_legend(override.aes=list(fill=NA))) +
      scale_x_date(
        name = " ", 
        labels = c('Fri\n27', 'Tue\n31', 'Sat\n4', 'Wed\n8', 'Sun\n12', 'Thu\n16', 'Mon\n20', 'Fri\n24'),
        breaks = seq.Date(as.Date("2021-08-27"), as.Date("2021-09-24"), by = "4 days")) +
      scale_y_continuous(
        name = " ",
        limits = c(0, 8),
        breaks = seq(0.0, 8.0, by = 2.0), 
        labels = c('0.0', '2.0', '4.0', '6.0', '8.0 kWh')) +
      annotate("segment", x = median(c(as.Date("2021-08-31"), as.Date("2021-09-01"))),
               xend = median(c(as.Date("2021-08-31"), as.Date("2021-09-01"))),
               y = 0, yend = 8.0, colour = 'gray88', size = 0.5) +
      annotate("rect",
               xmin = median(c(as.Date("2021-08-31"), as.Date("2021-09-01"))),
               xmax = median(as.Date("2021-09-02")),
               ymin = 7.6, ymax = 8.0, alpha = 0.5, colour = 'gray88', fill = 'white') +
      annotate("text",
               x = as.Date("2021-09-01"),
               y = 7.85,
               label = "Sep",
               size = 2.5,
               hjust = 0.2) +
      theme(plot.background = element_rect(fill = 'gray96'),
            panel.background = element_rect(fill = 'gray96'),
            panel.grid.major.x = element_blank(),
            panel.grid.minor.x = element_blank(),
            panel.grid.major.y = element_line(color = 'gray88',
                                              size = 0.3,
                                              linetype = 1),
            panel.grid.minor.y = element_blank(),
            axis.ticks = element_blank(),
            plot.title = element_text(size = 8, color = 'gray30', hjust = 0.5),
            axis.text.x = element_text(vjust = 5, size = 8),
            axis.text.y = element_text(hjust = 0, size = 8),
            legend.direction = "horizontal",
            legend.background = element_blank(),
            legend.box.background = element_rect(linewidth = 1),
            legend.title = element_blank(),
            legend.box = "horizontal",
            legend.position = "bottom")
    

    Created on 2023-03-06 with reprex v2.0.2