R ggplot 在图例项之间添加空格

标签 r ggplot2

<分区>

我有一个 ggplot2 并且正在尝试增加图例项之间的间距。

下面的代码生成下面的图:

library(tidyverse)
library(ggplot2)
year <- 2005:2015
variablea <- 1000:1010
variableb <- 1010:1020
df = data.frame(year, variablea, variableb)

df %>% gather(variable, value, -year) %>% 
  ggplot(aes(x = year, y = value, colour = variable, linetype = variable)) + 
  geom_line() +
  theme(
    legend.key=element_blank()
    ,legend.text=element_text(size=12)
    ,legend.position="bottom"
    ,legend.title=element_blank()
    ,panel.background = element_rect(fill = "transparent") # bg of the panel
    ,plot.background = element_rect(fill = "transparent") # bg of the plot
  ) 

enter image description here

然而,底部图例项目之间的差距太小了,让人不舒服。

我试过从其他问题中改编解决方案,但它们不起作用。

例如添加+ guides(fill=guide_legend(keywidth=0.1, keyheight=0.1, default.unit="inch"))Is there a way to change the spacing between legend items in ggplot2? 中所建议不起作用,因为它是折线图,因此线条只是扩展以填充额外的空间。我也尝试了链接问题中建议的第二种解决方案,但它似乎没有改变(目前我正在使用 + scale_fill_manual(values=c("red","blue"), labels= c("变量a","变量b"))).

此外,我不确定如何调整 Space between gpplot2 horizontal legend elements 中给出的解决方案,因为据我所知,我没有使用因子变量。

我能做什么?

最佳答案

您可以尝试以下操作:

df1 <- df %>% gather(variable, value, -year)
df1$variable <- paste0(df1$variable,"\t\t\t\t\t") # enter more tabs if needed
df1 %>% 
  ggplot(aes(x = year, y = value, colour = variable, linetype = variable)) + 
  geom_line() +
  theme(
    legend.key=element_blank()
    ,legend.text=element_text(size=12)
    ,legend.position="bottom"
    ,legend.title=element_blank()
    ,panel.background = element_rect(fill = "transparent") # bg of the panel
    ,plot.background = element_rect(fill = "transparent") # bg of the plot
  )  + guides(linetype = guide_legend(ncol = 2,keywidth=4))

enter image description here

关于R ggplot 在图例项之间添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42401568/

相关文章:

html - 如何增加 bookdown 中侧边栏菜单的宽度

r - R,将多行文本数据框架合并到一个单元格中

r - 在 R 中的序列中优雅地为 ggplot2 轴标签创建字符串

根据R中的id号复制行

r - 如何基于多列和条件进行模糊连接?

r - 在 ggplot2 theme_bw() 中不再向后拉网格线

r - 如何用空格引用变量名?

r - 无法打印到 pdf ggplot 图表

r - ggplot2 为几个 stat_functions 添加图例

r - 网页上的 Shiny 服务器错误 : An error has occurred The application failed to start. 应用程序在初始化期间退出