2

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

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

在此处输入图像描述

虚拟示例:

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

2 回答 2

1

我不知道ggpubr,它好像是一个包装器ggplot2。如果这是真的,并且/或者它已经实现了与 相同的功能ggplot2,那么您应该能够通过 来实现legend guide,请参见此处。我认为这是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(and fill) 可以工作,而shapeor不行linetype。如果情节需要是单色的,这将是相关的。这三个都应该作为分组因素同样有效。

有人有想法吗?

于 2019-03-10T18:13:45.653 回答
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"))
于 2019-03-10T18:57:40.533 回答