绘制ggplot2中geom_ raster()的边距图

时间:2016-04-08 13:56:07

标签: r ggplot2 raster

我正在尝试使用一些数据绘制栅格地图,并绘制此数据的边距图。 有点像levelplot() rasterVis函数,或者更好的颜色(反映图中的颜色)而不是一条线。下面将会清楚地看到我正在尝试做的事情。 rasterVis示例(带密度线):

http://i.stack.imgur.com/QiaUu.png

但是,我想使用ggplot2。下载data used in this example(8KB)。

我尝试使用grid.arrange()

library(ggplot2)
library(raster)
library(maps)
library(grid)
library(scales) #for muted()
library(gridExtra)

load("example.Rsave") #load data

#prepare data for the margin plot
var=tp_rlim; min=0; max=1; mid=0.5
varname <- colnames(var)[3]
zonal <- aggregate(var[,3], list(var$Lat), mean)
colnames(zonal) <- c("Lat", varname)

#plot the margin plot
ggzonal <- ggplot(zonal, aes(x="", y=Lat, fill=tp))+ 
             geom_raster() +
             theme(legend.position="none",
                   axis.title.x = element_blank(),
                   axis.title.y = element_blank(),
                   axis.ticks = element_blank(),
                   axis.text.x = element_blank(),
                   axis.text.y = element_blank()
                   ) +
             scale_fill_gradient2(limits=c(min, max), space="Lab", midpoint=mid)

#plot main plot
  gg <- ggplot(var, aes_string(x="Lon", y="Lat", fill=varname)) +
          geom_raster() +
          coord_quickmap(xlim = range(var$Lon), ylim = range(var$Lat)) + 
          scale_fill_gradient2(limits=c(min, max), space="Lab", midpoint=mid) +
            theme(legend.position="bottom",
                  legend.key.width = unit(1.5, "cm"),
                  legend.key.height = unit(0.3, "cm"),
                  legend.title=element_blank()
                  ) + 
            borders(region=unique(na.omit(map.where("world", var$Lon, var$Lat))), colour="black")

  grid.arrange(gg, ggzonal, ncol=2, widths=c(5, 1))

但结果并不令人满意: enter image description here

我也尝试使用ggExtra::ggMarginal,但是:

ggExtra::ggMarginal(gg)

enter image description here

或者:

ggExtra::ggMarginal(gg, type="histogram")

enter image description here

我该怎么做?

2 个答案:

答案 0 :(得分:3)

这可能有用,

# fix the ylim of annotation plot
gg2 = ggzonal + coord_cartesian(ylim = range(var$Lat)) 
# devtools::install_github("baptiste/egg")
library(egg)
ggarrange(gg, gg2, widths = c(10,1))

enter image description here

答案 1 :(得分:2)

使用精彩的cowplot包和找到的here指令,我们可以执行以下操作:

library(cowplot)

grobs <- ggplotGrob(gg + theme(legend.position="bottom"))$grobs
legend_b <- grobs[[which(sapply(grobs, function(x) x$name) == "guide-box")]]

prow <- plot_grid(gg + theme(legend.position="none"), ggzonal, align = 'h', rel_widths = c(5, 1))

plot_grid(prow, legend_b, ncol = 1, rel_heights = c(1, .2))
ggsave('stack.png', w = 5, h = 5)

结果:

enter image description here