Placing a Legend Title Above a Horizontal Legend Already Positioned at the Top of a Barplot ggplot

Viewed 35

Issue:

I have done a lot of research and tried many different solutions and I could not find an answer to my problem, at least not one that worked for me. I am attempting to place the legend title 'Species' above the horizontally placed legend positioned at the top of a barplot (see below) and for it to be centred.

For instance:

Solution 1

Solution 2

Solution 3

In general, I believe and I am using the correct ggplot() commands and I have tried following the examples from other StackOverflow questions. Whatever code I use, nothing happens and the title continues to remain at the lefthand side of the horizontal legend.

Would anyone be able to lend a hand?

Many thanks in advance.

R-Code

#Open Graphics Window
dev.new()

#Barplot
Whistle_Plot<-ggplot(Whistle_Subtype, aes(x = Whistle_Type_Sub, y = N, fill = Species)) + 
                            geom_bar(stat="identity", position=position_dodge(), width = 0.6) +
                            scale_fill_grey(start = 0.25, end = 0.75) +
                            theme(axis.text.x = element_text(angle = 75, hjust = 1), text = element_text(size=9)) + 
                            theme(panel.background = element_blank(), 
                            panel.grid.major = element_blank(), 
                            panel.grid.minor = element_blank(),
                            panel.border = element_blank()) + 
                            theme(axis.line.x = element_line(color="black", size = 0.8),
                            axis.line.y = element_line(color="black", size = 0.8)) + 
                            labs(size = 0.8, x = "Whistle Subtypes", y = "Counts of Whistle Subtypes") +
                            theme(legend.position = 'top', 
                                  legend.direction = "horizontal") + 
                                  guides(color = guide_legend(title.position = "top", 
                                   # hjust = 0.5 centres the title horizontally
                                   title.hjust = 0.5,
                                   label.position = "bottom")) 
                            #Set the limits of the y-axis scale
                            Whistle_Plot + scale_y_continuous(breaks=seq(0, 80, by=10)) 
                            

Barplot

enter image description here

1 Answers

If you switch to guides(fill = ...) you should be able do it.

Try:

guides(fill = guide_legend(title.position = "top", title.hjust=0.5)

(thanks to @teunbrand, for minor correction)

Related