I want to expose my problem, in order to give me some ways forward. My goal is to display a card with my full raster from this program:
library(raster) ; library(rgdal) ; library(sp);library(rgeos);library(ggplot2)
alti=raster("raster.tif")
hdf <- rasterToPoints(alti)
hdf <- data.frame(hdf)
colnames(hdf) <- c("Long","Lat","Altitude")
ggplot()+
layer(geom="raster",data=hdf,mapping=aes(Long,Lat,fill=Altitude))+
# draw boundaries
geom_path(color="black", linestyle=0.2)+
scale_fill_gradientn(name="A",colours=c("red","blue","green","grey","yellow","orange","black"), breaks=c(0,100,200,500,750,1000,2000))
At the end, I can not to adjust colors of my legend with ranges of value I have proposed.
I want to have this legend :
red : 0-100.
blue : 100-200.
green : 200-500.
grey : 500-750.
yellow : 750-1000.
orange : 1000-2000.
black : upper 2000.
example: normally for the range [1000-2000]
it's orange
, but in my result on the legend there are 3 colors grey
, yellow
and orange
.
I want the limits of my intervals should correspond to the value limits of the colors in the legend.
If you create a factor variable from your Altitude column and use scale_fill_manual()
, you can get it to work properly. It will also create nice labels for your legend automatically:
library(raster) ; library(rgdal) ; library(sp);library(rgeos);library(ggplot2)
alti=raster("raster.tif")
hdf <- rasterToPoints(alti)
hdf <- data.frame(hdf)
colnames(hdf) <- c("Long","Lat","Altitude")
tmp <- hdf$Altitude
hdf$Altitude <- ifelse(tmp <= 100, "0-100", hdf$Altitude)
hdf$Altitude <- ifelse(tmp > 100 & tmp <= 200, "100-200", hdf$Altitude)
hdf$Altitude <- ifelse(tmp > 200 & tmp <= 500, "200-500", hdf$Altitude)
hdf$Altitude <- ifelse(tmp > 500 & tmp <= 750, "500-750", hdf$Altitude)
hdf$Altitude <- ifelse(tmp > 750 & tmp <= 1000, "750-1000", hdf$Altitude)
hdf$Altitude <- ifelse(tmp > 1000 & tmp <= 2000, "1000-2000", hdf$Altitude)
hdf$Altitude <- ifelse(tmp > 2000, "Upper 2000", hdf$Altitude)
hdf$Altitude <- factor(hdf$Altitude)
g <- ggplot()+
layer(geom="raster",data=hdf,mapping=aes(Long,Lat,fill=Altitude))+
# draw boundaries
geom_path(color="black", linestyle=0.2)+
scale_fill_manual(values = c("red","blue","green","grey","yellow","orange","black"))