2017-09-27 105 views
-1

爲什麼不是閃避參數爲每個組創建多個酒吧?我正在尋找一個分組的酒吧情節,而不是我得到的那個。ggplot閃避不分組酒吧

df<-data.frame(c(40,23,18,41,15,14,38,21,1),c(rep("Do you agree with \nthe 'Hands Up' protestors ?",3),rep("Have the Police alienated themselves\n from the Public?",3),rep("Are the public ignoring the\n dangers Police face everyday?",3)),c("49%","28%","22%","59%","21%","20%","63%","35%","2%"),c(1,1,1,2,2,2,3,3,3)) 
colnames(df)<-c("values","names","percentages","group") 



ggplot(df,aes(names,values,group=group))+ 
    geom_bar(stat = "identity",position = "dodge",fill=rep(c("green","red","orange"),3))+ 
    geom_text(aes(label=percentages))+ 
    ylab("number of votes")+ 
    xlab("")+ 
    ggtitle("Police Opinion polls") 

我的結果:

enter image description here

我想要什麼:

enter image description here

回答

4

我認爲你需要在你的數據幀一列,實際上區分什麼不同的值(我猜測了)。然後,一個aes()呼叫內映射該列到填充審美爲ggplot正確躲閃的值:需要

df$response = rep(c("Yes", "No", "Unsure"), 3) 

dodger = position_dodge(width = 0.9) 
ggplot(df,aes(names,values, fill = response))+ 
    geom_bar(stat = "identity",position = dodger)+ 
    geom_text(aes(label=percentages), position = dodger)+ 
    ylab("number of votes")+ 
    xlab("")+ 
    ggtitle("Police Opinion polls") 

dodger = position_dodge(width = 0.9)的線,因爲geom_text必須被一個具有指定寬度手動迴避。

+0

我測試了你的代碼,位沒有得到我正在尋找的分組條形圖。我用一個例子更新了我的代碼,如果我的請求不清楚,我很抱歉 – Rilcon42

+2

我使用了您發佈的示例數據,在我的答案中添加了代碼並獲得了一個閃避的條形圖。你能解釋一下,你通過運行示例數據得到的結果是什麼,這樣我就可以確定哪裏出錯了? – Marius

+0

我的壞 - 我沒有注意到我們正在使用兩個不同的列df $響應。當你使用'response'時,我將它從'group'變量中取出 – Rilcon42