ggplot如何在绘制栅格时为不存在的整数设置填充值

时间:2018-05-01 10:46:46

标签: r ggplot2 raster

我正在绘制(Z)中的整数值作为光栅文件。在Z值中,数字6不存在,但是我希望为它指定填充颜色并在图例中显示它。怎么能我做到了吗?下面是数据,其中X和Y对应于经度和纬度。

      X     Y   Z
84  75.75 12.50 7
85  76.00 12.50 5
86  76.25 12.50 5
87  76.50 12.50 2
88  76.75 12.50 7
89  77.00 12.50 4
100 75.75 12.25 2
101 76.00 12.25 4
102 76.25 12.25 2
103 76.50 12.25 3
104 76.75 12.25 2
105 77.00 12.25 4
116 75.75 12.00 1
117 76.00 12.00 1
118 76.25 12.00 2
119 76.50 12.00 3
120 76.75 12.00 2
121 77.00 12.00 5
132 75.75 11.75 1
133 76.00 11.75 0
134 76.25 11.75 1
135 76.50 11.75 0
136 76.75 11.75 1
137 77.00 11.75 0
148 75.75 11.50 1
149 76.00 11.50 0
150 76.25 11.50 1
151 76.50 11.50 2
152 76.75 11.50 2
153 77.00 11.50 4

我曾尝试使用以下代码..

  [![p1 <-ggplot(XYZ.1)+ geom_raster(aes(X,Y,fill=Z)) +
    coord_equal()+theme_bw()+xlab("")+ylab("") +
    scale_fill_manual(values = c("grey50", "#f7f7f7", "#80b1d3","#7fc97f","#ffff99","#beaed4","#f0027f"),name= "Integer", guide = guide_legend(reverse = TRUE)) +
    scale_x_continuous(breaks=seq(75.625,77.125, 0.25), labels=c(paste(seq(75.625,77.125, 0.25),"°E", sep="")),expand = c(0, 0))+
    scale_y_continuous(breaks=seq(11.375,12.625,0.25), labels=c(paste(seq(11.375,12.625,0.25),"°N", sep="")),expand = c(0, 0)) +
    theme(axis.text.x = element_text(angle = 90, hjust = 1),panel.grid.major = element_blank(),
        panel.grid.minor = element_blank()) +
    theme(plot.title = element_text(hjust = 0.5,size = 10, face = "plain"),legend.title=element_text(size=10),legend.text=element_text(size=9))][1]][1] 

1enter image description here

1 个答案:

答案 0 :(得分:1)

Z定义为级别从0到7的因素,并在drop=FALSE内使用scale_fill_manual

XYZ.1$Z <- factor(XYZ.1$Z, levels=0:7)

p1 <- ggplot(XYZ.1)+ geom_raster(aes(X,Y,fill=Z)) +
   coord_equal() + theme_bw() + xlab("") + ylab("") +
   scale_fill_manual(values = c("grey50","#f7f7f7","#80b1d3","#7fc97f","#ffff99",
                                "#beaed4","red","#f0027f"), 
        name= "Integer", guide=guide_legend(reverse=TRUE), drop=FALSE) +
   geom_polygon(data=shp.Kabini.basin.bndry, aes(long,lat,group=group),
                colour="black", fill=NA)+
   scale_x_continuous(breaks=seq(75.625,77.125, 0.25), 
        labels=c(paste(seq(75.625,77.125, 0.25),"°E", sep="")),expand = c(0, 0))+
   scale_y_continuous(breaks=seq(11.375,12.625,0.25), 
        labels=c(paste(seq(11.375,12.625,0.25),"°N", sep="")),expand = c(0, 0)) +
   theme(axis.text.x = element_text(angle = 90, hjust = 1),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank()) +
   theme(plot.title = element_text(hjust = 0.5,size = 10, face = "plain"),
        legend.title=element_text(size=10), legend.text=element_text(size=9))
print(p1)

enter image description here