使用https://gist.github.com/low-decarie/5886616中的代码 可以生成双树状图瓦片图:
dual_dendogram_tile_plot(as.matrix(USarrests), main="USA Arrests")
问题:将垂直树状图与平铺图区域对齐。(和/或改进水平树状图的对齐方式)
这个问题涉及:
使用https://gist.github.com/low-decarie/5886616中的代码 可以生成双树状图瓦片图:
dual_dendogram_tile_plot(as.matrix(USarrests), main="USA Arrests")
问题:将垂直树状图与平铺图区域对齐。(和/或改进水平树状图的对齐方式)
这个问题涉及:
这是一个对齐更多基本 grobs 的示例,
library(ggplot2)
library(grid)
library(gtable)
p <- qplot(1,1)
g <- ggplotGrob(p)
panel_id <- g$layout[g$layout$name == "panel",c("t","l")]
g <- gtable_add_cols(g, unit(1,"cm"))
g <- gtable_add_grob(g, rectGrob(gp=gpar(fill="red")),
t = panel_id$t, l = ncol(g))
g <- gtable_add_rows(g, unit(1,"in"), 0)
g <- gtable_add_grob(g, rectGrob(gp=gpar(fill="blue")),
t = 1, l = panel_id$l)
grid.newpage()
grid.draw(g)
和你的grobs
@baptiste 的回答帮助我更好地理解了 gtable 结构以及如何修改它。下面我将我修改后的变体发布为(我自己的)重用的代码片段。
它find_panel()
用于获取面板范围,并将%>%
修改直接导入grid.draw
. 管道大大简化了gtable_*
函数的使用,因为它允许轻松取消注释单行并检查对最终绘图的影响。
library(ggplot2)
library(grid)
library(gtable)
library(dplyr)
p <- ggplot(tribble(~x,~y,~a,~b,
1, 1, "a1","b1",
1, 1, "a2","b1",
1, 1, "a2","b2"),
aes(x=x,y=y)) +
geom_point() +
facet_grid(vars(a),vars(b))
g <- ggplotGrob(p)
panels_extent <- g %>% find_panel()
g %>%
# Add red box to the very right, by appending a column and then filling it
gtable_add_cols(widths = unit(1,"cm"), pos = -1) %>%
gtable_add_grob(rectGrob(gp=gpar(fill="red")),
t = panels_extent$t, b = panels_extent$b,
l = -1, r = -1) %>%
# Add green box to the top, by prepending a row and then filling it
# Note the green box extends horizontally over the first panel as well
# as the space in between.
gtable_add_rows(heights = unit(1,"cm"), pos = 0) %>%
gtable_add_grob(rectGrob(gp=gpar(fill="green")),
t = 1, b = 1,
l = panels_extent$l, r = panels_extent$l+1) %>%
{grid.newpage();grid.draw(.)}