在ggplot2中更改geom_bar的图例键的形状

时间:2016-11-07 16:19:26

标签: r plot ggplot2

我正在尝试从geom_bar图表更改图例键的形状。我在线查看了多个答案,但发现它们在这种情况下不起作用。让我解释一下这个问题:

df1 = data.frame(person = c("person1", "person2", "person3"),
             variable = "variable1",
             value = c(0.5, 0.3, 0.2))

df2 = data.frame(person = c("person1", "person2", "person3"),
             variable = "variable2",
             value = c(-0.3, -0.1, -0.4))

我正在尝试制作一个堆积的条形图,其中一边是负面的。使用ggplot2我得到:

library(ggplot2)
ggplot() + geom_bar(data = df1, aes(x = person, y = value, fill = variable), stat = "identity") +
  geom_bar(data = df2, aes(x = person, y = value, fill = variable), stat = "identity") +
  scale_fill_manual(values = c("steelblue", "tomato"), breaks = c("variable1","variable2"),
                labels = c("Variable 1", "Variable 2"))

然后看起来像这样:

enter image description here

现在在右侧,图例默认显示正方形。有没有办法将其改为例如?

在线我发现这通常的方式是使用

guides(fill = guide_legend(override.aes = list(shape = 1)))

或类似的变化。然而,这似乎不起作用。如果有人能提供帮助那就太好了,我已经被困了一段时间了。

1 个答案:

答案 0 :(得分:4)

您可以添加一个没有数据的geom_point图层(仅用于创建图例),并使用show.legend = FALSE隐藏条形图中不需要的矩形图例:

df3 = data.frame(person = as.numeric(c(NA, NA)),
                 variable = c("variable1", "variable2"),
                 value = as.numeric(c(NA, NA)))

ggplot() + 
  geom_bar(data = df1, aes(x = person, y = value, fill = variable), stat = "identity", show.legend = FALSE) +
  geom_bar(data = df2, aes(x = person, y = value, fill = variable), stat = "identity", show.legend = FALSE) +
  geom_point(data = df3, aes(x = person, y = value, color = variable), size=8) +
  scale_fill_manual(values = c("steelblue", "tomato"), breaks = c("variable1","variable2")) +
  scale_color_manual(values = c("steelblue", "tomato")) +
  theme(legend.key = element_blank())

enter image description here