2016-12-28 16 views
2

どのように私はggplot2 2.2.0 1つのラインでタイトルや凡例を揃えていますか?Rのggplot2:1行のタイトルと凡例

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") 

titleプロパティとしてlineheightおよび/またはvjustを変更すると、何もしていないようです。

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 、 "行"))、legend.box.margin =マージン(-1,0,0,0、 "行")) '? – 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

関連する問題