I'm trying to make a choropleth map of counties in the US. My values have a large range, and are highly 0 inflated, so I would like to create custom bins for the legend and coloring. Ideally this would be using ggplot. I would also like to keep a standard structure for the legend so that I can use the same legend for multiple choropleths with different data.
The legend might be something 0, 1-20, 21-50, 51-150, 151-300, 301-800, with each "bin" having its color derived from Spectral or some other continuous color palette.
scale_color_steps()
, scale_fill_brewer()
and other similar functions, even with breaks
and limits
or n.breaks
, don't seem to work. Any ideas?
library(choroplethr)
library(choroplethrMaps)
library(ggplot2)
data(county.regions)
df <- tibble(region = county.regions$region, value = c(rep(0,2000), rep(1,1000), sample(2:800, 143)))
county_choropleth(df) +
scale_colour_steps(palette='Spectral', n.breaks = 8)
The simple solution to achive your desired result is to set num_colors = 1
in country_choropleth
.
From the docs of country_choropleth
:
num_colors The number of colors to use on the map. A value of 0 uses a divergent scale (useful for visualizing negative and positive numbers), A value of 1 uses a continuous scale (useful for visualizing outliers), and a value in [2, 9] will use that many quantiles.
By default num_colors = 7
which means that the continuous data gets discretized so that adding a continuous fill scale throws an Error: Binned scales only support continuous data.
Setting num_colors = 1
the data don't gets binned and we can apply a custom continuous fill scale:
library(choroplethr)
library(choroplethrMaps)
library(ggplot2)
data(county.regions)
set.seed(42)
df <- tibble::tibble(region = county.regions$region, value = runif(3143, 0, 800))
breaks <- c(0, 20, 50, 150, 300, 800)
county_choropleth(df, num_colors = 1) +
scale_fill_stepsn(colors = RColorBrewer::brewer.pal(5, "Spectral"), breaks = breaks)
county_choropleth(df, num_colors = 1) +
scale_fill_viridis_b(breaks = breaks)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.