Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot2: Title and legend in one line

Tags:

r

ggplot2

How do I align the title and legend in one line in 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")

Changing the lineheight and/or vjust as title property doesn't seem to do anything.

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))
like image 435
rmf Avatar asked Dec 19 '25 13:12

rmf


1 Answers

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

enter image description here

like image 136
Axeman Avatar answered Dec 21 '25 06:12

Axeman