简体   繁体   English

R:使用 ggplot 增加图例项之间的垂直间距

[英]R: Increase vertical spacing between legend items using ggplot

I created a line chart using ggplot.我使用 ggplot 创建了一个折线图。 I want to increase the vertical spacing between my legend items (text and symbols)我想增加图例项(文本符号)之间的垂直间距

I found this about this problem.我发现了这个问题。 However, isn't there a more simple (ie without writing a function) solution to this problem?然而,对于这个问题,难道没有更简单(即不写函数)的解决方案吗?

I tried the command legend.spacing.y but that only moves the entire legend up and down and not the spacing between the items.我尝试了命令legend.spacing.y但这只会上下移动整个图例,而不是项目之间的间距。

Also, I tried: theme(legend.text = element_text(margin = margin(t = 1, unit = "cm")))) However, this only moves the text and not the items.另外,我尝试了: theme(legend.text = element_text(margin = margin(t = 1, unit = "cm"))))但是,这只会移动文本而不是项目。

Could anybody please help?有人可以帮忙吗?

Thanks!谢谢!

We can also do this in a pipe with tidyverse我们也可以使用tidyverse在 pipe 中执行此操作

library(ggplot2)
library(dplyr)
mtcars %>%
    mutate(cyl = factor(cyl)) %>%
    ggplot(aes(mpg, wt, colour = cyl)) +
   geom_point() +
  theme(
        legend.key.size = unit(1.5, 'lines'),
        legend.key = element_rect(size = 5, color = 'white'))

This can be useful:这可能很有用:

library(ggplot2)
#Code
ggplot(data = mtcars, aes(mpg, wt, colour = factor(cyl))) +
  geom_point() +
  theme(
        legend.key.size = unit(1.5, 'lines'),
        legend.key = element_rect(size = 5, color = 'white'))

Output: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM