简体   繁体   English

如何更改ggplot2 R栅格图例的标度颜色

[英]How to change the scale color of the legend of raster ggplot2 R

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 . 例如:通常在[1000-2000]范围内,它是orange ,但是在图例中,我的结果是greyyelloworange 3种颜色。 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. 如果您从“高度”列中创建一个因子变量并使用scale_fill_manual() ,则可以使其正常运行。 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"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM