R 颜色条图例在面图中的位置

问题描述 投票:0回答:1

我在

ggplot
中有以下带有颜色条的简单多面图 MWE。似乎颜色条总是放置在两个没有条带的面板之间垂直居中。是否可以更改此行为,使其居中(包括条带),或者与条带顶部对齐?

df <- expand.grid(
  a = c(1, 2, 3),
  b = c(1, 2, 3),
  g = c("a", "b", "c", "d")
)

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

ggplot(df, aes(x = a, y = b, fill = v)) +
  facet_wrap(. ~ g) +
  geom_tile(color = "black") +
  scale_y_discrete(expand = c(0,0)) +
  scale_x_discrete(expand = c(0,0)) +
  theme(legend.position = "right",
        legend.title = element_blank(),
        strip.background.x = element_rect(
          colour = "black", linewidth = 0.5)) +
  guides(fill = guide_colourbar(
    barheight = unit(2, "in")))

这种行为在更改时可以清楚地看到,例如,将条形高度从 2 更改为 3.75。为了简单起见,我使用了硬编码的条高,但实际上可以按照这个示例计算出正确的条高,并进行一些调整以考虑条带的额外区域。

r ggplot2 facet-wrap
1个回答
0
投票

通过

theme
功能,您可以设置一些图例属性,包括位置和间距(请参阅
?theme
)。

示例:

    your_ggplot_object + 
      theme(legend.margin = margin(t = 0, r = 0, b = 0, l = 1, unit = "cm"),
            legend.justification = c(1, 1) ## horizontal, vertical from 0 to 1
            )

© www.soinside.com 2019 - 2024. All rights reserved.