如何更改光栅ggplot2 R图例的比例颜色

How to change the scale color of the legend of raster ggplot2 R

我想公开我的问题,以便给我一些前进的方向。 我的目标是显示一张卡片,其中包含来自 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))

最后,我无法根据我建议的值范围调整图例的颜色。

我想要这个图例:

  red : 0-100.
  blue : 100-200.
  green : 200-500.
  grey : 500-750.
  yellow : 750-1000.
  orange : 1000-2000.
  black : upper 2000.

示例:通常 [1000-2000] 范围是 orange,但在我的图例结果中有 3 种颜色 greyyelloworange. 我希望我的区间限制应该对应于图例中颜色的值限制。

如果您从 Altitude 列创建一个因子变量并使用 scale_fill_manual(),您可以让它正常工作。它还会自动为您的图例创建漂亮的标签:

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"))