Graham G
Graham G

Reputation: 584

Create map plot with discrete colors

I have just started to use ggplot2 and have created a map overlaid with data represented by a continuous color map. The data runs from 0.205 to 0.756. However, I would like to plot the data with 'n' discrete colors, and with the mid point at 0.5.

I have modified the relevant part of my code to the following:

...
df %>% # dataframe
mutate(value_cut = cut_interval(value, n = 6)) %>%
ggplot() -> gg

gg <- gg + geom_polygon(aes(x = long, y = lat, group = group,
                            fill = value_cut), size = 0.25, color = NA)
gg <- gg + viridis::scale_fill_viridis(discrete = TRUE,direction=-1)
...
print(gg)

which generates the following plot: map with discrete data levels

It is almost there, but I would like to be able to specify an 'even' number of unique colors and have the mid-point set at 0.5. I have tried a number of different approaches but, usually end up with errors.

Any help appreciated.

Upvotes: 0

Views: 3234

Answers (1)

Graham G
Graham G

Reputation: 584

I am including my answer in case it helps someone in future.

Following advice from ulfelder, I used R functions cut() and scale_fill_manual(), when the relevant code becomes

...
df %>%
  mutate(value_cut = cut(value, breaks=c(0.2,0.35,0.5,0.65,0.8))) %>%
  ggplot() -> gg

# Create the coloured map using the ggplot2 package
# color=NA omits demarcation lines between constituencies
gg <- gg + geom_polygon(aes(x = long, y = lat, group = group,
                            fill = value_cut),
                        size = 0.25, color = NA)
cols <- c("yellow","gold","lightblue","royalblue")
gg <- gg + scale_fill_manual(values = cols)
...
print(gg)

which generates the following plot:

enter image description here

as required.

More discrete colors can be readily achieved by increasing the number of breaks when calling the cut() function, and increasing the number of colors in the cols array.

Many thanks to ulfelder for the excellent and prompt advice.

Upvotes: 1

Related Questions