2017-02-22 43 views
1

我有一個ggplot2,並且正在嘗試增加圖例項之間的間距。R ggplot在圖例項之間添加空格

下面的代碼產生以下情節:

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

然而在底部圖例項之間的間隙太接近爲舒適。

我試圖從其他問題的解決方案,但他們不工作。

例如,如Is there a way to change the spacing between legend items in ggplot2?中建議的+ guides(fill=guide_legend(keywidth=0.1, keyheight=0.1, default.unit="inch"))不能正常工作,因爲它是一個線圖,所以線條只是簡單地擴展以填充額外的空間。我也嘗試了鏈接問題中提出的第二種解決方案,但它似乎沒有改變(目前我正在使用+ scale_fill_manual(values=c("red","blue"), labels=c("variablea ","variableb ")))。

此外,我不確定如何修改Space between gpplot2 horizontal legend elements中給出的解決方案,因爲我沒有使用因子變量,據我所知。

我該怎麼辦?

回答

2

你可以嘗試像以下:

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