R ggplot2:标题和图例一行显示

3
我该如何在ggplot2 2.2.0中将标题和图例对齐在同一行?

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 似乎没有任何效果。
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
也许可以添加 theme(plot.title = element_text(margin = margin(0,0,0,0, "line")), legend.box.margin = margin(-1,0,0,0, "line")) - lukeA
1个回答

7
几乎完美,但类似这样的东西可以工作:
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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接