Home > Blockchain >  How to include a legend to a ggplot2?
How to include a legend to a ggplot2?

Time:01-30

Given this data here:

p <- ggplot(mpg, aes(displ, cty))   geom_point()   facet_grid(drv ~ cyl)
g <- ggplot_gtable(ggplot_build(p))
strip_both <- which(grepl('strip-', g$layout$name))
fills <- c("red","green","blue","yellow","red","green","blue","yellow")
k <- 1
for (i in strip_both) {
j <- which(grepl('rect', g$grobs[[i]]$grobs[[1]]$childrenOrder))
g$grobs[[i]]$grobs[[1]]$children[[j]]$gp$fill <- fills[k]
k <- k 1
}
grid.draw(g)

I want to add a legend for the colors of the facets:

 as shown here

CodePudding user response:

One option to achieve your desired result would be with an auxiliary geom_point layer which draws nothing but is only used to map a variable with your desired four categories on the fill aes. Doing so will automatically add a fill legend for which we could set your desired colors using scale_fill_manual. Additionally I switched the key_glyph for the point layer to draw_key_rectto mimic your desired style for the legend keys and added na.rm to silent the warning about removed NAs:

library(ggplot2)
library(grid)

p <- ggplot(mpg, aes(displ, cty))   geom_point()   facet_grid(drv ~ cyl)  
  geom_point(data = data.frame(x = NA_real_, y = NA_real_, fill = c("AB", "D", "FF", "v")), 
             aes(x = x, y = y, fill = fill), na.rm = TRUE, key_glyph = "rect")  
  scale_fill_manual(values = c("AB" = "red", D = "yellow", FF = "blue", v  = "green"), name = NULL)  
  theme(legend.position = "bottom")

g <- ggplot_gtable(ggplot_build(p))
strip_both <- which(grepl('strip-', g$layout$name))
fills <- c("red","green","blue","yellow","red","green","blue","yellow")
k <- 1
for (i in strip_both) {
  j <- which(grepl('rect', g$grobs[[i]]$grobs[[1]]$childrenOrder))
  g$grobs[[i]]$grobs[[1]]$children[[j]]$gp$fill <- fills[k]
  k <- k 1
}
grid.draw(g)

  •  Tags:  
  • Related