使用构面时,ggplot 颜色条与顶部对齐

car*_*arl 1 r facet ggplot2

我正在使用ggplot包含颜色条的多面图。我想将颜色条缩放到多面图的大小。按照 @AllanCameron 在这篇文章中关于单个图的想法并调整函数以考虑条带大小和图之间的空间,我能够正确计算出图例的大小。因此,无论ncol、panel.spacing.y或 ,图例的大小都被正确指定。strip.text.x。

但是,默认情况下,图例位于两个没有条带的图之间的中心。到目前为止,通过legend.position或调整图例并不能帮助正确指定它。如何将图例与图表顶部(即条带顶部)正确对齐(有关预期输出,请参阅右侧的图)?legend.justification

例子

我仅在右侧图表中将图例对齐到顶部,而没有使用外部图形程序调整大小。因此,虽然左侧图表中的图例高度看起来太小,但实际上尺寸还不错。

library(ggplot2)

df <- expand.grid(
  x = c(1, 2, 3),
  y = c(1, 2, 3),
  g = c("one", "two", "three", "four")
)

set.seed(1)
df$v <- runif(nrow(df), min = 0, max = 1)

make_fullsize <- function() structure("", class = "fullsizebar")

ggplot_add.fullsizebar <- function(obj, g, name = "fullsizebar") {
  h <- ggplotGrob(g)$heights
  panel <- which(grid::unitType(h) == "null")
  panel_height <- unit(1, "npc") - sum(h[-c(panel, (panel-1), grep("lines", h))])

  g + 
    guides(fill = guide_colorbar(barheight = panel_height,
                                 title.position = "right")) +
    theme(legend.title = element_text(angle = -90, hjust = 0.5))
}

ggplot(df, aes(x = x, y = y, fill = v)) +
  facet_wrap(. ~ g, ncol = 2) +
  geom_tile(color = "black") +
  scale_y_discrete(expand = c(0,0)) +
  scale_x_discrete(expand = c(0,0)) +
  theme(panel.spacing.y = unit(1, "lines"),
        strip.text.x = element_text(size = 15, margin = margin(2,0,2,0, "cm")),
        strip.background.x = element_rect(
        colour = "black", linewidth = 1)) +
  make_fullsize()
Run Code Online (Sandbox Code Playgroud)

ste*_*fan 5

基于@AllanCameron 的原始代码和我的改编方法,我们可以轻松计算出正确的条形高度。然而,要达到您想要的结果,需要通过进行一些额外的调整theme。legend.justification将设为bottom并删除顶部和底部legend.margin:

library(ggplot2)

make_fullsize <- function() structure("", class = "fullsizebar")

ggplot_add.fullsizebar <- function(obj, g, name = "fullsizebar") {
  p <- ggplotGrob(g)
  
  h <- p$heights
  
  ix_panel <- grep("^panel", p$layout$name)
  ix_strip <- grep("^strip", p$layout$name)
  
  panel_t <- min(p$layout[ix_strip, "t"])
  panel_b <- max(p$layout[ix_panel, "b"])
  
  barheight <- unit(1, "npc") - sum(h[-seq(panel_t, panel_b)])
  
  g +
    guides(fill = guide_colorbar(
      barheight = barheight,
      title.position = "right"
    )) +
    theme(
      legend.justification = "bottom",
      legend.margin = margin(0, 5.5, 0, 5.5),
      legend.title = element_text(angle = -90, hjust = 0.5)
    )
}

ggplot(df, aes(x = x, y = y, fill = v)) +
  facet_wrap(. ~ g, ncol = 2) +
  geom_tile(color = "black") +
  scale_y_discrete(expand = c(0, 0)) +
  scale_x_discrete(expand = c(0, 0)) +
  theme(
    panel.spacing.y = unit(1, "lines"),
    strip.text.x = element_text(size = 15, margin = margin(2, 0, 2, 0, "cm")),
    strip.background.x = element_rect(
      colour = "black", linewidth = 1
    )
  ) +
  make_fullsize()

ggsave("foo.png", width = 5, height = 5)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述