使用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()
Run Code Online (Sandbox Code Playgroud)
您可以查询设备尺寸并进行legend.key.width相应更改。所以你的my_theme函数可以是:
my_theme <- function() {
theme_bw() +
theme(legend.position = "bottom",
legend.key.width = unit(dev.size()[1] / 10, "inches"))
}
Run Code Online (Sandbox Code Playgroud)
所以现在当我们这样做时:
ggplot(mpg) +
geom_point(aes(cty, hwy, color = year)) +
my_theme()
Run Code Online (Sandbox Code Playgroud)
我们得到:
但是如果我们缩小范围并再次调用上面的代码,我们会得到
或者,如果我们将其设置得很宽并再次调用它,我们会得到: