Custom ggplot2 choropleth colours using brewer palette

137 views Asked by At

I want to create a choropleth map of to show the broadband speed across England's region. For the colour palette I want to use the Brewer colour package. I changed my variable of interest into a factor variable because as a numeric variable I got an error message.

This is the code I used to create the graph with the Brewer package:

library(ggplot2)

# convert to factor
df_regions_ofcom$over30 <- as.factor(df_regions_ofcom$over30)

# ggplot 
ggplot()+
  geom_polygon(data = df_regions_ofcom,
               aes(x=long,y=lat,group=group,fill=over30),
               color = "black", # add black boarder around regions
               size = 0.1)+ # adjust thickness of line 
  theme_void()+ # remove coordinates data
  labs(title = "Percentage of lines receiving download speeds over 30 Mbps in England (May 2022)",
       caption = "Data: Ofcom")+
  theme(
    text=element_text(family="A"), # set font 
    plot.title = element_text(size= 14, hjust=0.01, face = "bold"), # change caption font size & align left & bold font 
    plot.caption = element_text(size=12, hjust=0.01), # change caption font size & align left
    legend.title = element_text(size=10, face = "bold"), # change legend title font size
    legend.text = element_text(size=10), # change legend text font size
    legend.spacing.y = unit(.3, "cm")) + # increase space after legend space 
  scale_fill_brewer(palette = "BuGn")

My graph looks like this:

enter image description here

As you can see there are too many groups and too many decimal points.

  1. how do I change the number of categories shown (e.g. 5 quintiles only)

  2. how do I change the number of decimal points to 2 integers only?

The basic graph without the Brewer package looks like this:

enter image description here

Suggestions to correct my code to apply the brewer package

1

There are 1 answers

1
margusl On

The issue here is not directly Brewer-releated, but supplying continuous values to a discrete scale (scale_fill_brewer) and trying to fix Continuous value supplied to discrete scale error with as.factor().

Discrete scale_*_brewer comes with a cupule of friends that will work with continuous values: distiller and fermenter. Can't test it without a reproducible example, but remove the factor conversion and try replacing

scale_fill_brewer(palette = "BuGn")

with

scale_fill_fermenter(n.breaks = 5, labels = scales::label_percent(accuracy = .01),  palette = "BuGn")

( scales::label_percent() expects values on 0 ... 1 scale )