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

wwl*_*wwl 3 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
  ) 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

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

我试图从其他问题中调整解决方案,但它们不起作用。

例如,+ guides(fill=guide_legend(keywidth=0.1, keyheight=0.1, default.unit="inch"))按照有没有办法更改 ggplot2 中图例项之间的间距中的建议添加?不起作用,因为它是一个折线图,所以这些线只是扩展以填充额外的空间。我也尝试了链接问题中建议的第二种解决方案,但它似乎没有改变(目前我正在使用+ scale_fill_manual(values=c("red","blue"), labels=c("variablea ","variableb ")))。

另外,我不确定如何调整在 gpplot2 水平图例元素之间的空间中给出的解决方案,因为据我所知,我没有使用因子变量。

我能做什么?

San*_*Dey 5

您可以尝试以下操作:

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))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明