2016-11-07 123 views
3

我试图从geom_bar图中更改图例键的形状。我在网上查看了多个答案,但发现它们在这种情况下不起作用。让我来解释这个问题:更改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)) 

我试图做一个堆叠barplot其中一方为负。使用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

我很惊讶,有如果没有解决方法,不是一种方法。 –

回答

3

你可以不带数据添加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

+0

谢谢!它确实能做到这一点,尽管它非常显着,但这似乎是实现这一目标的唯一方法,正如皮埃尔指出的那样。 –