I am working in the next code: ggplot()+ geom_sf(data = DPEst_DH, aes(size = di1a), col="orangered")
that works.
But I want a colored legend.
In other words, I want apply the same field at two aesthetics, size and color but keeping one legend.
...+ geom_sf(data = DPEst_DH, aes(color=di1a, size=di1a))
With that code line I have the next output but I want to know if is possible to have something like the last image.
One option to achieve your desired result would be to make your di1a
column a discrete variable using e.g. cut
and to set the colors and sizes via scale_xxx_manual
.
Making use of the nc
shape file shipped with the sf
package as example data:
library(ggplot2)
library(dplyr)
# Example data
nc_center <- sf::st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE) %>%
sf::st_centroid()
# Bin numeric variable
labels <- pretty(range(nc_center$AREA))
breaks <- c(labels, Inf)
nc_center <- nc_center %>%
mutate(area = cut(AREA, breaks = breaks, labels = labels, right = FALSE))
# Color and size palette
colors <- c("#132B43", "#56B1F7") # Default ggplot2 blue colors used for color gradient
pal <- colorRampPalette(colors)(length(labels))
pal_size <- seq(1, 6, length.out = 5) # c(1, 6): Default range for size scale
ggplot() +
geom_sf(data = nc_center, aes(color = area, size = area)) +
scale_color_manual(values = pal) +
scale_size_manual(values = pal_size)