简体   繁体   English

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

[英]Change the shape of legend key for geom_bar in ggplot2

I'm trying to change the shape of the legend key from a geom_bar graph. 我正在尝试从geom_bar图表更改图例键的形状。 I've looked at multiple answers online but found they didn't work in this case. 我在线查看了多个答案,但发现它们在这种情况下不起作用。 Let me explain the problem: 让我解释一下这个问题:

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

I'm trying to make a stacked barplot where one side is negative. 我正在尝试制作一个堆积的条形图,其中一边是负面的。 Using ggplot2 I get: 使用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"))

It then looks like this: 它看起来像这样:

在此输入图像描述

Now on the right the legend shows squares by default. 现在在右侧,图例默认显示正方形。 Is there a way to change this into a circle for instance? 有没有办法将其改为例如?

Online I've found the way this usually works is by using 在线我发现这通常的工作方式是使用

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

Or similar variations. 或类似的变化。 However this doesn't seem to work. 然而,这似乎不起作用。 If anybody can help that would be great, I've been stuck for quite a while now. 如果有人可以提供帮助那就太好了,我已经被困了一段时间了。

You could add a layer of geom_point with no data (just to create a legend) and hide the unwanted rectangular legend from the bars using show.legend = FALSE : 您可以添加一个没有数据的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())

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM