Ответ 1
Здесь можно вращать грани независимо. Мы создаем список, содержащий отдельный поворотный график для каждого уровня month
, а затем используйте grid.arrange
для компоновки четырех графиков. Я также удалил легенду с отдельных сюжетов и построил легенду отдельно. Следующий код содержит вспомогательную функцию для извлечения легенды.
Я извлекаю объект легенды в глобальную среду в функции lapply
ниже (не говоря уже о повторении извлечения несколько раз). Вероятно, лучший способ, но этот способ был быстрым.
library(gridExtra)
# Helper function to extract the legend from a ggplot
# Source: http://stackoverflow.com/info/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()