rggplot2geom-raster

Add separate legend for geom_raster and geom_path


I am plotting a raster and overlaying it with two polygons. I want to plot legends for each shapefile separately (i.e., Buffer zones legend and one legend for each polygon). I used show.legend = TRUE inside geom_path but it's not giving me what I want. I am using this code.

gplot(pfiles) + 
  geom_raster(aes(fill = factor(value))) +
  geom_path(data=ward, aes(long, lat, group=group), color = "black") +
  geom_path(data=buffer, aes(long, lat, group=group), color = "red") +
  facet_wrap(~ variable, ncol = 4) +
  scale_fill_manual(values = c("darkorchid", "chartreuse3", "cornflowerblue", "goldenrod2"), 
                      na.value="transparent", na.translate = F) +
  guides(fill = guide_legend(title = "Buffer Zones")) +
  #scale_color_identity(guide = "legend") +
  theme_bw() +
  theme(axis.text = element_blank(), legend.position = "right", legend.direction = "vertical",
        axis.title = element_blank(),
        legend.key.height = unit(2, "cm"), legend.key.width = unit(1, "cm"),
        legend.title = element_text(size = 22, face = "bold"), legend.text = element_text(size = 20), 
        strip.text = element_text(size = 18, face = "bold"),
        plot.title = element_text(size = 20, face = "bold"),
        plot.subtitle = element_text(size = 15), plot.caption = element_text(size = 12, face = "bold.italic"),
        panel.background = element_rect(fill = "transparent")) +
  labs(title = "Variables for Identification of Potential Urban Development Zones",
       subtitle = "Land Price and Ground Water Level represent price and water depth respectively; Others represent Euclidean Distance") +
  coord_equal()

enter image description here


Solution

  • In ggplot2 geoms don't have a legend. Instead legends reflect aesthetics or scales. The geom only determines the shape of the key used in the legend, e.g. a geom_point will be depicted as a point, a geom_path as a line, ... This said, if you want to have a legend you have to map on aesthetics.

    To get a legend depicting the different colored geom_paths you could map a constant value on the color aesthetic and then assign your desired colors to these constants using scale_color_manual.

    The following code is not tested but should give you your desired result:

    ggplot(pfiles) +
      geom_raster(aes(fill = factor(value))) +
      geom_path(data = ward, aes(long, lat, group = group, color = "ward")) +
      geom_path(data = buffer, aes(long, lat, group = group, color = "buffer")) +
      scale_color_manual(values = c(ward = "black", buffer = "red"))