删除ggplot图例中的重复标签

时间:2018-08-27 15:17:13

标签: r ggplot2 legend

我想使用交互作用在图例中创建带有子组的图。我用零值创建了一些虚假数据来创建子标题。

我的样本数据:

library(ggplot2)
df <- data.frame(value = runif(27, 0, 1),
                 x = rep(1:3, each = 3),
                 group1 = rep(c(letters[1:3])),
                 group2 = rep(c("fake", "X", "Y"), each = 9))
# introducing fake data
df[df$group2 == "fake", "value"] <- 0
df$group2 <- relevel(df$group2, ref = "fake")

我几乎能够创建所需的剧情:

# labels
lbl1 <- c(expression(bold("HEADING 1")), paste("LABEL 1", 1:2),
          expression(bold("HEADING 2")), paste("LABEL 2", 1:2),
          expression(bold("HEADING 3")), paste("LABEL 3", 1:2))
fills <- c("white", "red1", "red3",
           "white", "blue1", "blue3",
           "white", "green1", "green3")
colo <- c("white", "black", "black",
          "white", "black", "black",
          "white", "black", "black")

ggplot(df, aes(x = x, y = value,
               fill = interaction(group2, group1), 
               colour = interaction(group2, group1))) +
  geom_col(position = "dodge") +
  scale_fill_manual("", values = fills, label = lbl1)  +
  scale_colour_manual("", values = colo, label = lbl1)

enter image description here

但是,我不想在子组中有LABEL 1 1LABEL 1 2等,我只希望有LABEL 1LABEL 2

指定此类标签时,我无法创建此类图:

lbl2 <- c(expression(bold("HEADING 1")), paste("LABEL", 1:2),
          expression(bold("HEADING 2")), paste("LABEL", 1:2),
          expression(bold("HEADING 3")), paste("LABEL", 1:2))

ggplot(df, aes(x = x, y = value,
               fill = interaction(group2, group1), 
               colour = interaction(group2, group1))) +
  geom_col(position = "dodge") +
  scale_fill_manual("", values = fills, label = lbl2)  +
  scale_colour_manual("", values = colo, label = lbl2)

enter image description here

明确地说,这是期望的输出:

enter image description here

2 个答案:

答案 0 :(得分:2)

您具有非唯一标签,因为您要引入一个假组来分隔绘图上的列。 根据{{​​1}}帮助:

  

给出标签的字符向量(长度必须与断点相同)

比例尺代码可能会调用discrete_scale到字符向量,您最终得到的向量中的标签少于在怪异的图例上导致的中断。

似乎您应该使用构面来获得相似的结果,而不是使用hack(伪造的组):

unique

enter image description here

如果您确实想要确切的图,则必须使用更多的技巧来更改标签来修改# Remove the "fake" group 2 df1 <- df[df$group2 != "fake",] ggplot(df1, aes(x = group1, y = value, fill=group2)) + geom_col(position = "dodge", color ="black")+ scale_fill_manual( values =c("red","green"),labels = c("Lable 1", "Lable 2")) + scale_x_discrete(labels =c("H1", "H2", "H3")) + facet_wrap(x~., strip.position = "bottom")

gtable

enter image description here

答案 1 :(得分:0)

下面的示例几乎代表了您的最后一张图像,但条带周围的黑色边框除外,但这也许对您来说还好吗?

lbl1 <- c(("HEADING 1"), paste("LABEL", 1:2),
          ("HEADING 2"), paste("LABEL", 1:2),
          ("HEADING 3"), paste("LABEL", 1:2))

fills <- c("white", "red1", "red3",
           "white", "blue1", "blue3",
           "white", "green1", "green3")

ggplot(df, aes(x = x, y = value,
               fill = interaction(group2, group1))) +
  geom_col(position = "dodge", show.legend = TRUE) +
  scale_fill_manual(values = fills, label = lbl1) +
  theme(legend.title = element_blank())