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

Nil*_*kay 5 plot r 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))
Run Code Online (Sandbox Code Playgroud)

我正在尝试制作一侧为负的堆叠条形图。使用 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"))
Run Code Online (Sandbox Code Playgroud)

然后它看起来像这样:

在此处输入图片说明

现在右侧的图例默认显示正方形。例如,有没有办法把它改成一个圆圈?

在网上我发现这通常工作的方式是使用

guides(fill = guide_legend(override.aes = list(shape = 1)))
Run Code Online (Sandbox Code Playgroud)

或类似的变体。但是,这似乎不起作用。如果有人可以提供帮助,那就太好了,我已经被困了很长一段时间了。

dww*_*dww 7

您可以添加一个没有数据的 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())
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明