2016-07-13 188 views
0

所以,我的數據集是這樣的:ggplot barplot - Y軸百分比

id group age length Bnull_subject Bnull_object Bnull_other 
1 NS 23 NA 3 3 1 
2 NS 23 NA 1 4 0 
3 NS 58 NA 4 4 1 
4 NS 24 NA 2 3 1 
5 NS 32 NA 3 2 0 
6 NS 24 NA 4 1 1 
7 NS 25 NA 5 2 0 
8 NS 24 NA 3 2 0 
9 NS 25 NA 3 2 0 
22 ATT 26 [5-7] 4 4 0 
23 ATT 28 [5-7] 4 1 0 
24 ATT 28 [5-7] 5 3 1 
25 ATT 28 [5-7] 1 5 1 
26 ATT 26 [5-7] 4 2 0 
27 ATT 29 [5-7] 3 2 0 

我試圖創建ggplot一個barplot與y軸persentage,但我不能得到它的一些正常工作原因..這是我用

dset.bnull <- subset(dset, select = c(group, length, Bnull_subject, Bnull_object, Bnull_other)) 


    library(reshape2) 
    library(ggplot2) 
    library(scales) 
mdat <- melt(dset.bnull[c(1,3:5)], id.vars="group") #?melt <- Converts an object into a molten data frame 

head(mdat) #Shows top observations of your data 

ggplot(mdat, aes(variable, value, fill = group)) + 
    geom_bar(aes(y = (value)/sum(value)), stat = "identity", position=position_dodge(1)) + 
    scale_y_continuous(labels = percent) + #Use percentage on y axis 
    xlab("Referent") + #Rename x axis 
    ylab("Percentage of Answers") + #Rename y axis 
    guides(fill=guide_legend(title="Experimental \nGroup")) 

我得到的情節是這樣的代碼......(它是錯的很明顯)

enter image description here

約我應該做的任何幫助嗎?

預先感謝您

+0

嘗試將所述計算('Y =(值)/ SUM(值))')在ggplot呼叫:'ggplot(MDAT,AES(X =變量,Y =值/總和(值)) ,fill = group))+ ...'並將其從'geom_bar()'調用中移除。 – Phil

+0

@Phil我已經試過了,並沒有工作... –

+1

嘗試熔化之前計算百分比,並把它們作爲值GGPLOT2 –

回答

0

我想你剛收到你們的melt錯誤。

嘗試

mdat <- melt(dset.bnull[c(1:2, 5:7)], id.vars=c("id", "group")) 

,並從geom_bar呼叫中除掉

position=position_dodge(1) 


更新:從您的評論我猜你很舒服使用dplyr。總結數據後繪圖會更直觀。

plot_data = mdat %>% group_by(group, variable) %>% summarise(total = sum(value)) 

ggplot(plot_data, aes(fill = group)) + 
    geom_bar(aes(x = variable, 
       y = (total)/sum(total)), 
       stat = "identity", 
       position = "dodge") + 
    scale_y_continuous(labels = percent) + 
    xlab("Referent") + 
    ylab("Percentage of Answers") + 
    guides(fill=guide_legend(title="Experimental \nGroup")) 
+0

我的壞..我忘了說在此之前,該子集IA ..集dset.bnull < - 子集(DSET,選擇= C(組,長度,Bnull_subject,Bnull_object,Bnull_other)) –

+0

它弄亂百分比,因爲設置'位置= 「躲閃」'覆蓋默認'位置= 「棧」',因此,所有的酒吧在彼此頂部(並且您只能看到每組中的最大值)。總結數據擺脫了任何棘手的問題「閃避和堆疊」問題。 –

+1

工作,謝謝!我的頭腦非常混亂,我根本沒有考慮過使用dplyr。只是爲了糾正一個小問題..在調用ggplot後,你需要一個'+'而不是','。再次感謝。 –