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

时间:2015-07-07 14:54:23

标签: r ggplot2 legend raster

我想揭露我的问题,以便给我一些前进的方法。 我的目标是使用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种颜色greyyellow和{{ 1}}。 我希望我的间隔限制应该对应于图例中颜色的值限制。

1 个答案:

答案 0 :(得分:1)

如果您从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"))