我想我有个棘手的案子。我在用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)但是我真正想要的是,让每个面以一定的角度旋转(例如15°),以反映这样一个事实,那就是我的场不是按照北完全定向的(即顶部不是北,底部不是南)。在ggplot2或任何与网格相关的工具中,是否有可能自动完成此操作?即使是自动保存图像的各个方面,旋转它们,并在新的页面上打印旋转的图像将足以满足我的需要。下面是我想要获得的图像示例(图像编辑器中的小面旋转了15°):http://imgur.com/RYJ3EaR

发布于 2015-12-18 17:19:46
这是一种独立旋转小面的方法。我们为每个级别的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()

https://stackoverflow.com/questions/34358801
复制相似问题