ggplot在光栅图像周围创建一个白色背景

时间:2018-04-18 11:05:07

标签: r ggplot2 raster

我在使用ggplot绘制栅格数据方面存在一些问题。

(1)它在图表周围创建了白色背景。我不想要图像周围的白色边框。

(2)图中的NA值应在图例中显示为缺失值。

 X      Y           Z
1  75.875 12.375   2.6510951
2  76.125 12.375   5.4310212
3  76.375 12.375   3.6985113
4  76.625 12.375  -3.2694589
5  76.875 12.375  -1.6689374
6  75.875 12.125  -9.1670256
7  76.125 12.125  -4.7482244
8  76.375 12.125   1.1797042
9  76.625 12.125   0.1593383
10 76.875 12.125  -3.2102890
11 75.875 11.875 -11.0326909
12 76.125 11.875  -7.9738824
13 76.375 11.875  -0.6844057
14 76.625 11.875  -2.8986147
15 76.875 11.875  -0.1624192
16 75.875 11.625          NA
17 76.125 11.625  -2.3323547
18 76.375 11.625   8.6410179
19 76.625 11.625  -2.3619503
20 76.875 11.625          NA

  library(ggplot2)
  library(raster)
  library(cowplot)
  library(scales)

scale = range(XYZ.1$Z,na.rm=TRUE)

   b = round(seq(scale[1],scale[2],length.out = 3),digits = 1)

   p1<-ggplot(XYZ.1)+ geom_raster(aes(X,Y, fill=Z)) +
      coord_equal()+theme_bw()+xlab("")+ylab("") +
      scale_fill_gradient2(low = "blue", high = "red", mid = "white",
                           midpoint = 0, na.value = "black",
                           name="",limits= c(scale[1],scale[2])) +
      scale_x_continuous(breaks=seq(75.75,77.0, 0.25), labels=c(paste(seq(75.75,77.0, 0.25),"°E", sep="")))+
      scale_y_continuous(breaks=seq(11.5,12.5,0.25), labels=c(paste(seq(11.5,12.5,0.25),"°N", sep=""))) +
      theme(axis.text.x = element_text(angle = 45, hjust = 1),panel.grid.major = element_blank(),
            panel.grid.minor = element_blank())+
      ggtitle("reference : gauge") +
      theme(plot.title = element_text(hjust = 0.5,size = 10, face = "plain"),legend.title=element_text(size=10),legend.text=element_text(size=9))+
      theme(plot.margin = unit(c(0,0,0,0), "in"))

Raster Image

1 个答案:

答案 0 :(得分:1)

按照this answer中显示的第二个解决方案中的想法,您可以添加一个“虚拟”点数图层,以获取color值用于NA值的图例。

这是一个“虚拟”图层,因为我们添加它,但是然后通过将点的大小设置为0来移除它。点是将color美学映射到aes geom_point内的字符串{1}}。

然后,我们可以使用scale_color_manual将名称设置为我们想要的名称(我使用“NA”),然后通过legend.key中的theme将背景设为黑色。

使用expand = c(0, 0)作为轴刻度会删除面板边框。

以下是对此的看法的基本概念:

ggplot(XYZ.1) + 
     geom_raster(aes(X, Y, fill = Z)) +
     coord_equal() +
     geom_point( aes(X, Y, color = ""), size = 0) +
     scale_fill_gradient2(low = "blue", high = "red", mid = "white",
                          midpoint = 0, na.value = "black",
                          name = "") +           
     scale_colour_manual(name = "NA", values = NA) +
     theme(legend.key = element_rect(fill = "black")) +
     scale_y_continuous(expand = c(0, 0) ) +
     scale_x_continuous(expand = c(0, 0) )

enter image description here

相关问题