Creating a ggplot of a map with categorised data overlayed

Preformatted text

I am trying to create a map displaying the probability a species will occur in x location the data was in raster format and I converted it into a dataframe. It is on a global scale and I created a lovely ggplot with a gradient scale using the following code:

ggplot(data=df, aes(y=Latitude, x=Longitude)) +
geom_tile(aes(fill=MAP)) +
theme_bw() +
coord_equal() +
scale_fill_gradientn("Occurrence Probability", colours=c("light grey","red"))+
theme(axis.title.x = element_text(size=16),
axis.title.y = element_text(size=16, angle=90),
axis.text.x = element_text(size=14),
axis.text.y = element_text(size=14),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.position = "right",
legend.key = element_blank()

And this all worked fine!
I then wanted to categorise the probability and did so using the following code:

df$category[df$MAP < 0.05] <- "Absent"
df$category[df$MAP > 0.05 & df$MAP < 0.5] <- "Low probability of presence"
df$category[df$MAP > 0.5] <- "High probability of presence"

this also worked!
But trying to plot this new categorised data onto a map proved a lot more difficult, does anyone have any suggestions?
I couldn't work out which scale function to use from ggplot or how to even format one for discrete data!


To help us help you, could you please prepare a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

stringsAsFactors = FALSE,
Longitude = c(-35.0208333333333,
Latitude = c(83.6041666666667,
MAP = c(0.000245005998294801,
category = c("Absent","Absent","Absent",

Is that correct?

More as a comment than answer; {ggplot2} works fine with vector data, and the geom_sf() is joy to use.

But ggplot2 doesn't like raster data. Base plot via {raster} and / or tm_raster() from {tmap} are often easier choices for convincing raster data visualization.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.