R ggpubr:将图例标题移动到图例键上方

R ggpubr: move legend title above the legend keys

我正在为 ggpubr 中的图例位置而苦苦挣扎。我知道我可以修改图例位置p.e。通过 ggpar(legend = "bottom")。但是,如何将图例标题放在图例键上方?

ggplot2中,似乎guide_legend(title.position = "top")应该这样做,但是如何让它与ggpubr一起工作? (感谢 @c06n 和 link 此处:https://ggplot2.tidyverse.org/reference/guide_legend.html)。我想结合 ggplot2ggpubr 但我不知道为什么。

虚拟示例:

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

我不知道 ggpubr,它似乎是 ggplot2 的包装器。如果那是真的,and/or 它实现了与 ggplot2 相同的功能,您应该可以通过 legend guide 实现,请参阅 here。我认为是 title.position 你需要调整。

如果您无法通过 ggpubr 实现这一点,我建议您改用 ggplot2,也许可以根据您的需要调整主题。

编辑。 @markus 有答案,所以把它全部放在一个地方:

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

@Bruno Pinheiro 提出了一个有趣的问题,即为什么只有 color(和 fill)有效,而 shapelinetype 无效。如果情节需要是单色的,这将是相关的。这三个因素作为分组因素应该同样有效。

有人知道吗?

这些选项在这里有效。

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

我不知道为什么,但如果我为另一种美学设置指南,图例标题位置不会改变:

p + guides(shape = guide_legend(title.position = "top"))
p + guides(linetype = guide_legend(title.position = "top"))

这是一个很好的问题 ggplot2 专家。

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