简体   繁体   English

R ggplot2:一行中的标题和图例

[英]R ggplot2: Title and legend in one line

How do I align the title and legend in one line in ggplot2 2.2.0 ? 如何在ggplot2 2.2.0中将标题和图例对齐在一行?

在此输入图像描述

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

Changing the lineheight and/or vjust as title property doesn't seem to do anything. 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))

Hardly perfect, but something like this will work: 很难完美,但这样的事情会起作用:

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

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM