2016-11-07 39 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

謝謝!它確實能做到這一點,儘管它非常顯着,但這似乎是實現這一目標的唯一方法,正如皮埃爾指出的那樣。 –