Search code examples
rggplot2colors

How to change the box color in the colour guide in ggplot maps?


I used:

 geom_polygon(aes(color = as.factor(VALE), 
               fill = ES.PC)) + scale_color_manual(values = c("Vale do Ribeira" = 'black', "Other regions of SP" = 'white'))

to separate different regions in a ggplot2 map, but I need to change the color of the guide boxes from gray to white

those boxes with the "Vale do Ribeira" and "Other Regions" circled in red

those circled in red


Solution

  • One option would to use the override.aes argument of guide_legend to set the fill color of the color scale.

    Adapting the default example from ?geom_polygon:

    library(ggplot2)
    
    ggplot(datapoly, aes(x = x, y = y)) +
      geom_polygon(aes(fill = value, group = id, color = factor(id2))) +
      guides(color = guide_legend(override.aes = list(fill = "white")))
    

    DATA

    ids <- factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3"))
    
    values <- data.frame(
      id = ids,
      value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5)
    )
    
    positions <- data.frame(
      id = rep(ids, each = 4),
      x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3,
            0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),
      y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5,
            2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2)
    )
    datapoly <- merge(values, positions, by = c("id"))
    
    datapoly$id2 <- grepl("^1", datapoly$id)