2016-12-28 109 views
2

如何在ggplot2 2.2.0的一行中對齊標題和圖例?R ggplot2:一行中的標題和圖例

enter image description here

library(ggplot2) 
library(dplyr) 
library(tidyr) 

dfr <- data.frame(x=factor(1:20),y1=runif(n=20)) %>% 
    mutate(y2=1-y1) %>% 
    gather(variable,value,-x) 

ggplot(dfr,aes(x=x,y=value,fill=variable))+ 
    geom_bar(stat="identity")+ 
    labs(title="Badass title")+ 
    theme(legend.position="top", 
     legend.justification="right") 

改變lineheight和/或vjust如title屬性似乎並沒有做任何事情。

ggplot(dfr,aes(x=x,y=value,fill=variable))+ 
    geom_bar(stat="identity")+ 
    labs(title="Badass title")+ 
    theme(legend.position="top", 
     legend.justification="right", 
     plot.title = element_text(lineheight=-5,vjust=0)) 
+1

也許加上'主題(plot.title = element_text(保證金=保證金(0,0,0,0 ,「line」)),legend.box.margin = margin(-1,0,0,0,「line」))'? – lukeA

回答

4

幾乎完美,但像這樣將工作:

ggplot(dfr,aes(x=x,y=value,fill=variable))+ 
    geom_bar(stat="identity")+ 
    labs(title="Badass title")+ 
    guides(fill = guide_legend(direction = "horizontal")) + 
    theme(legend.position=c(1, 1.05), 
     legend.justification="right") 

enter image description here