After cutting my raster according to a polygon using the "mask" function :
ras <- mask(ras0, polygon)
I want to present the raster (link below) with ggplot. However, I have a problem with the "NA" values that located in outside of my cut raster.
https://depots.univ-perp.fr/get?k=9sh9zKXDpRTkVQslvJk
I add the option na.value = "transparent" in "scale_fill_manual" to put the NA values in transparency on my map, but the legend of NA always remains!
How to delete in the legend the text "NA" and the box in gray color corresponding?
Is there a solution to remove difinetely the NA values when using the "mask" function or when registering with "Writeraster" to avoid this problem when displaying with ggplot ?
Here is the program used to display the map:
library(raster)
ras<-raster("ras.tif")
# map
gplot(ras)+
geom_tile(aes(fill=factor(value, labels=c("A", "B", "C", "D", "E", "F","G"))))+
scale_fill_manual(values = c("red", "#22751a", "#48c665", "#d3d532", "#d78d0d", "#f6e600","#65d6ef"),
name= "Legend", na.value="transparent")+
coord_cartesian(xlim = c(-7, 12),ylim = c(32, 38)) +
#bg
theme(panel.background = element_rect(colour = "black", fill="lightblue"))
Thank you in advance
It seems that scale_fill_manual
shows NA values when used factors. A way to define factors that you really want to show is to use other parameters breaks
and labels
with a vector of correspondence. If I use your code this would be:
# Vector of correspondence
cols <- c("A" = "red", "B" = "#22751a", "C" = "#48c665",
"D" = "#d3d532", "E" = "#d78d0d", "F" = "#f6e600","G" = "#65d6ef")
# plot
gplot(ras) +
geom_tile(aes(fill=factor(value, labels=c("A", "B", "C", "D", "E", "F","G"))))+
scale_fill_manual(values = cols,
breaks = c("A", "B", "C", "D", "E", "F","G"),
labels = c("A", "B", "C", "D", "E", "F","G"),
name= "Legend") +
coord_cartesian(xlim = c(-7, 12),ylim = c(32, 38)) +
theme(panel.background = element_rect(colour = "black", fill="lightblue"))
However, you can use it in another way while attributing directly values (as character) of your raster to a specific color and then names (I had to add a new color because you have 8 levels in your raster):
# Vector of correspondence
cols.nb <- c("0" = "blue", "1" = "red", "2" = "#22751a", "3" = "#48c665",
"4" = "#d3d532", "5" = "#d78d0d", "6" = "#f6e600",
"7" = "#65d6ef")
# Plot
gplot(ras) +
geom_tile(aes(fill = as.character(value))) +
scale_fill_manual(values = cols.nb,
breaks = 0:7,
labels = c("A", "B", "C", "D", "E", "F","G","H"),
name = "Legend") +
coord_cartesian(xlim = c(-7, 12),ylim = c(32, 38)) +
theme(panel.background = element_rect(colour = "black", fill="lightblue"))