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

时间:2019-03-10 18:00:35

标签: r ggplot2 ggpubr

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

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

enter image description here

虚拟示例:

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

1 个答案:

答案 0 :(得分:1)

这些选项在这里起作用。

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