Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot legend title top center

Tags:

r

legend

ggplot2

Is there a way to put legend title on top and center compared to the legend itself?

Example:

cons2 <- data.table(
value_date  = c(as.Date('2013-04-30'),as.Date('2013-04-30'),as.Date('2013-06-13'),as.Date('2013-06-13')),
ticker = c('AAPL','FTW','AAPL','FTW'),
discount = c(0.34,0.10,0.25,0.20),
b = c(0.40,0.55,.60,0.90),
yield = c(0.08,0.04, 0.06,0.03))


headers <- cons2[ticker == 'AAPL' & value_date == '2013-06-13']

p <- ggplot(cons2) 
p <- p + geom_point(aes(yield,b, size = discount, color=factor(value_date))) 
p <- p + guides(size = "none")
p <- p + scale_colour_manual(values = c("#1c2f80","#779438"))
p <- p + geom_text(data = headers, aes(yield, b, label=ticker), size = 4)
p <- p + geom_smooth(data = cons2[value_date == '2013-06-13'], aes(yield, b), method="lm", se=FALSE)
p <- p + geom_line(data = cons2, aes(yield, b, group = ticker))
p <- p + theme(legend.position="bottom")
p <- p + guides(colour=guide_legend(title.position="top"))
p
like image 963
Børge Klungerbo Avatar asked Jun 17 '13 19:06

Børge Klungerbo


People also ask

How do I change the position of my legend in R?

position. You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left .

How do I change the legend title in ggplot2?

Method 1: Change Legend Title using guides() Function. Now if we want to change Legend Title then we have to add guides and guide_legend functions to the geom_point function. Inside guides() function, we take parameter named 'color' because we use color parameter for legend in ggplot() function.


1 Answers

You can play with title.hjust parameter like this :

p <- p + guides(colour=guide_legend(title.position="top", 
                                     title.hjust =0.5))

enter image description here

like image 150
agstudy Avatar answered Oct 14 '22 11:10

agstudy