ggplot2中的facet旋转

Seb*_*der 10 r raster ggplot2

我想我有一个棘手的案子.我正在及时绘制进化植物疾病水平,使用geom_raster:x和y是任意场坐标,z是在几个时间点测量的疾病水平,我希望将每个日期绘制在不同的方面.到目前为止,没问题.下面是模拟数据集和代码:

library(ggplot2)
data <- data_frame(month=factor(rep(c("march","april","may","june"), each=100), levels=c("march","april","may","june")),
              x=rep(rep(1:10, each=10), 4),
              y=rep(rep(1:10, 10), 4),
              z=c(rnorm(100, 0.5, 1), rnorm(100, 3, 1.5), rnorm(100, 6, 2), rnorm(100, 9, 1)))
ggplot(data, aes(x=x, y=y, fill=z)) +
  geom_raster(color="white") +
  scale_fill_gradient2(low="white", mid=mean(range(dat$z)), high="red") +
  scale_x_discrete(limit=1:10, expand = c(0, 0)) +
  scale_y_discrete(limit=1:10, expand = c(0, 0)) +
  coord_equal() +
  facet_wrap(~month)
Run Code Online (Sandbox Code Playgroud)

但我真正喜欢的是让每个小平面以一定角度(例如15°)旋转,以反映我的场不是完全根据北方定向的事实(即,顶部不是北方,而是底部不是南方).ggplot2或任何与网格相关的工具是否有可能自动执行此操作?即使是将各个方面保存到图像,旋转它们以及在新页面上打印旋转图像的自动方式也足以满足我的需求.这是我想要获得的图像示例(在图像编辑器中旋转15°的面):http: //imgur.com/RYJ3EaR旋转刻面

eip*_*i10 16

这是一种独立旋转刻面的方法.我们创建一个列表,其中包含每个级别的单独旋转图month,然后用于grid.arrange将四个图一起布局.我还从各个图中删除了图例并分别绘制了图例.下面的代码包含一个提取图例的辅助函数.

我在lapply下面的函数中将图例对象提取到全局环境中(更不用说多次重复提取).可能有更好的方法,但这种方式很快.

library(gridExtra)

# Helper function to extract the legend from a ggplot
# Source: http://stackoverflow.com/questions/12539348/ggplot-separate-legend-and-plot
g_legend<-function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  legend
}

# Create a list containing a rotated plot for each level of month
pl = lapply(unique(data$month), function(m) {

  # Create a plot for the current level of month
  p1 = ggplot(data[data$month==m,], aes(x=x, y=y, fill=z)) +
    geom_raster(color="white") +
    scale_fill_gradient2(low="white", high="red", 
                         limits=c(floor(min(data$z)), ceiling(max(data$z)))) +
    scale_x_discrete(limit=1:10, expand = c(0, 0)) +
    scale_y_discrete(limit=1:10, expand = c(0, 0)) +
    coord_equal() +
    facet_wrap(~month) 

  # Extract legend into global environment
  leg <<- g_legend(p1)

  # Remove legend from plot
  p1 = p1 + guides(fill=FALSE)

  # Return rotated plot
  editGrob(ggplotGrob(p1), vp=viewport(angle=-20, width=unit(0.85,"npc"), 
                                       height=unit(0.85,"npc")))                    
})

# Lay out the rotated plots and the legend and save to a png file
png("rotated.png", 1100, 1000)
grid.arrange(do.call(arrangeGrob, c(pl, ncol=2)),
             leg, ncol=2, widths=c(0.9,0.1))
dev.off()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述