I have a ggplot2 code which I used to apply frequently to my spatial dataframes:
borders <- sf::st_as_sf(maps::map("world", plot = FALSE, fill = TRUE))
xmin1 = range(Per_yr$Lon)[1]
xmax1 = range(Per_yr$Lon)[2]
ymin1 = range(Per_yr$Lat)[1]
ymax1 = range(Per_yr$Lat)[2]
DF <- ggplot(Per_yr) +
geom_sf(data = borders, fill= "white")+
geom_tile(aes(x=Lon, y=Lat, fill= as.character(Total)))+
geom_sf(data = borders,fill = NA, colour = "dark green", size=0.2)+
coord_sf(xlim = c(xmin1, xmax1), ylim = c(ymin1, ymax1))+
scale_fill_manual(values = c("0" = "light grey", "1" = "#fcba03", "2"= "#e8940c", "3"="#DB6C05", "4"= "#e8550c", "5" = "#ad1320", "6" = "dark red",
"7"= "#F87F65", "8"="#f772b0", "9"="#e02b73", "10" = "#611975", "11"="#8d49cc", "12" = "#b595e6",
"13"= "#122da6", "14" = "blue", "15"="steel blue", "16" = "#609E90", "17" = "#0cb8e8", "18" = "#b7eb34", "19"="#90eb10",
"20"= "#89dc69", "21"="#57c27e", "22" = "#b7c50e", "23"= "#799c11", "24"= "#207852", "25"="#134d19"))+
scale_x_longitude(ticks = 2) +
scale_y_latitude(ticks = 2)
print(DF)
Here is a sample from my dataframe, Per_yr:
Lon Lat Total
24.0 35.3 13
24.0 35.4 8
24.0 35.5 3
24.0 37.7 5
24.0 37.8 5
24.0 38.0 7
24.0 38.1 8
The above code used to work fine, with the legend appearing in the exact same order I define the color assigned categories in scale_fill_manual. However, after I updated my R version to the new 4.3.1, and reinstalled tidyverse, ggplot started alphabeticising my legends.
From earlier stackoverflow questions, I tried different approaches to avert this, one of them below:
xmin1 = range(Per_yr$Lon)[1]
xmax1 = range(Per_yr$Lon)[2]
ymin1 = range(Per_yr$Lat)[1]
ymax1 = range(Per_yr$Lat)[2]
df <- data.frame(colorscale, names_colorscale)
df$names_colorscale <- as.numeric(df$names_colorscale)
legend_ord <- levels(with(df, reorder(colorscale, names_colorscale)))
DF <- ggplot(Per_yr) +
geom_sf(data = borders, fill= "white")+
geom_tile(aes(x=Lon, y=Lat, fill= as.character(Total)))+
geom_sf(data = borders,fill = NA, colour = "dark green", size=0.2)+
coord_sf(xlim = c(xmin1, xmax1), ylim = c(ymin1, ymax1))+
scale_fill_manual(values = legend_ord)+
scale_x_longitude(ticks = 2) +
scale_y_latitude(ticks = 2)
print(DF)
However I couldn't stop ggplot from alphabeticising.
Has anyone encountered a similar problem with a means to solve it?
P.S. Also after the update R Studio (running on Windows 11) keeps on showing my plots in an external pop-up window instead of the Plots pane on the lower right hand corner. If anyone of you know why it's happening (nothing in here is relevant, or works for me) and how I can fix it, I would greatly appreciate a way back to my old way of doing things :)