如何使 ggplot2 中的色条宽度为面板宽度的一半?

3
使用ggplot2,是否有一种方法可以指定基于绘图面板大小缩放的颜色条宽度?
也就是说,legend.key.width可以提供什么,以使得关键字的相对宽度保持不变,而与图形的大小无关?
ggplot(mpg) +
  geom_point(aes(cty, hwy, color = year)) +
  theme(legend.position = "bottom",
        legend.key.width = unit(0.1, "npc")) # not relative

# or could it be done with a custom theme?
my_theme <- function() {
  theme_bw() %+replace%
    theme(legend.position = "bottom", ?)

ggplot(mpg) +
  geom_point(aes(cty, hwy, color = year)) +
  my_theme()

1个回答

6
你可以查询设备大小并相应地更改legend.key.width。因此,你的my_theme函数可以是:
my_theme <- function() {
  theme_bw() +
    theme(legend.position = "bottom", 
          legend.key.width = unit(dev.size()[1] / 10, "inches"))
}

现在当我们执行以下操作时:

ggplot(mpg) +
  geom_point(aes(cty, hwy, color = year)) +
  my_theme()

我们得到:

enter image description here

但是,如果我们将情节缩小并再次调用上述代码,我们会得到

enter image description here

或者如果我们将其变得非常宽并再次调用它,我们会得到:

enter image description here


谢谢,这个很好用。 为什么半宽度的条需要将设备的宽度除以10而不是2? - BetaScoo8
1
@BetaScoo8 我不知道为什么会发生这种情况。dev.size()应该是以英寸为单位的,并且我们在unit调用中指定了“inches”,因此将其除以二应该可以工作。我不确定这是否是ggplot中计算grob大小的内部方式的问题。 - Allan Cameron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接