在https://gist.github.com/low-decarie/5886616找到代码 可以生成双树枝状瓷砖图:
dual_dendogram_tile_plot(as.matrix(USArrests),main =“美国逮捕”)
问题:将垂直树形图与瓷砖绘图区域对齐。 (和/或改善水平树状图的对齐)
这个问题涉及:
left align two graph edges (ggplot)
Specifying ggplot2 panel width
Plot correlation matrix into a graph
答案 0 :(得分:26)
这是一个对齐更基本的grob的例子,
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
答案 1 :(得分:0)
@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(.)}