首页 > 解决方案 > 如何将 ggplot2 colourbar 的宽度指定为面板宽度的一半?

问题描述

使用 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()

标签: rggplot2

解决方案


您可以查询设备大小并进行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()

我们得到:

在此处输入图像描述

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

在此处输入图像描述

或者,如果我们把它弄得很宽并再次调用它,我们会得到:

在此处输入图像描述


推荐阅读