Reputation: 4090
I am struggling with the legend position within ggpubr. I know that I can modify the legend position p.e. by ggpar(legend = "bottom")
. But, how to place legend title above the legend keys?
In ggplot2
, it seems that guide_legend(title.position = "top")
should do this, but how to make it work with ggpubr
? (thanks to @c06n and link here: https://ggplot2.tidyverse.org/reference/guide_legend.html). I would like to combine the ggplot2
and ggpubr
but I don't know exactly why.
Dummy example:
df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
dose=rep(c("D0.5", "D1", "D2"),2),
len=c(6.8, 15, 33, 4.2, 10, 29.5))
# Plot "len" by "dose" and
# Change line types and point shapes by a second groups: "supp"
p<- ggline(df2, "dose", "len",
linetype = "supp", shape = "supp",
color = "supp", palette = c("#00AFBB", "#E7B800"))
# Seems not working
ggpar(p,
linetype = guide_legend(title = "My title", title.position = "top"))
Upvotes: 3
Views: 4052
Reputation: 176
I do not know ggpubr
, it seems like a wrapper for ggplot2
. If that is true, and/or it has implemented the same functionality as ggplot2
, you should be able to achieve that via legend guide
, see here. I think it is title.position
you need to adjust.
If you cannot achieve that with ggpubr
, I suggest using ggplot2
instead, perhaps adjusting the theme to your needs.
Edit. @markus has the answer, so to put it all in one place:
p <- ggline(df2, "dose", "len",
linetype = "supp",
shape = "supp",
color = "supp",
palette = c("#00AFBB", "#E7B800")) +
guides(color = guide_legend(title.position = "top",
title.hjust = 0.5))
Interesting question though from @Bruno Pinheiro as to why only color
(and fill
) will work, but not shape
or linetype
. This would be relevant if the plot needs to be monochrome. All three should work equally well as grouping factors.
Does anyone have an idea?
Upvotes: 4
Reputation: 1014
These options are working here.
With ggpubr
:
df2 <- data.frame(supp=rep(c("VC", "OJ"), each=3),
dose=rep(c("D0.5", "D1", "D2"),2),
len=c(6.8, 15, 33, 4.2, 10, 29.5))
library(ggpubr)
p <- ggline(df2, "dose", "len",
linetype = "supp", shape = "supp",
color = "supp", palette = c("#00AFBB", "#E7B800"))
p + guides(colour = guide_legend(title.position = "top"))
I don't know why, but if i set the guide for another aesthetic the legend title position do not change:
p + guides(shape = guide_legend(title.position = "top"))
p + guides(linetype = guide_legend(title.position = "top"))
It's a good question to be made for ggplot2
experts.
And here is the same working in ggplot2
:
library(ggplot2)
ggplot(df2, aes(x = dose, y = len, colour = supp)) +
geom_line(aes(group = supp, linetype = supp)) +
geom_point(aes(shape = supp)) +
scale_colour_manual(values = c("#00AFBB", "#E7B800")) +
theme_classic() +
theme(legend.position = "top") +
guides(colour = guide_legend(title.position = "top"))
Upvotes: 1