2017-02-20 107 views
2

我一直在尋找解決方案,但沒有一個已有的問題適合我的問題。R:用barpot,ggplot或plotly堆積的酒吧情節

我有data.frame:

Pat <- c(1,1,1,1,1,1,2,2,2,2,2,2) 
V_ID <- c(1,1,6,6,9,9,1,1,6,6,9,9) 
T_ID <- c("A","B","A","B","A","B","A","B","A","B", "A","B") 
apples <- c(1,1,1,1,1,1,1,1,1,1,1,1) 
bananas <- c(2,2,2,2,2,2,2,2,2,2,2,2) 
cranberries <- c(3,3,3,3,3,3,3,3,3,3,3,3) 

df <- data.frame(Pat,V_ID, T_ID, apples, bananas, cranberries) 

我試圖繪製:

barplot(as.matrix(df[,4:6]) , 
    main="tobefound", horiz = FALSE,width = 1, 
    names.arg=colnames(df[,4:6]), 
    las=2, 
    col = c("blue", "red"), 
    legend = df[,3], 
    args.legend = list(x="topleft"), 
    beside= FALSE) 

BARPLOT

enter image description here

我需要兩個變化:一是 我所有的l ike擁有所有的「B」(所以每個堆棧中的紅色部分)堆積在一起,然後堆積在藍色的頂部。二:有沒有通過

legend = df[1:2,3], 

降低傳說只有A和B的一次,除了解決這個問題的一種方式,我也正在尋找使用plotly或ggplot的解決方案。

感謝,

+0

是[這](http://stackoverflow.com/questions/20349929/stacked-bar-plot-in-r?rq=1)你在尋找什麼? – iled

+0

不可以。以前看過你的建議。我的目標是讓所有「A」和「B」通過顏色堆疊在一起。 – Rivka

回答

3

一是重塑:

df_long <- tidyr::gather(df, 'key', 'value', apples:cranberries) 

然後劇情:

ggplot(df_long, aes(key, value, fill = T_ID)) + geom_col(col = 'black') 

enter image description here

或許無邊界:

ggplot(df_long, aes(key, value, fill = T_ID)) + geom_col() 

enter image description here

+0

正是我在找的東西。謝謝 ! – Rivka

3

使用基本圖形,你需要通過T_ID第一排序df

df = df[order(df$T_ID), ] 

barplot(as.matrix(df[,4:6]) , 
     main="tobefound", horiz = FALSE,width = 1, 
     names.arg=colnames(df[,4:6]), 
     las=2, 
     ylim = c(0,40), 
     col = 1+as.numeric(as.factor(df$T_ID)), 
     border = NA, 
     beside= FALSE) 

box() 
legend('topleft', fill = 1+as.numeric(as.factor(levels(df$T_ID))), legend = levels(as.factor(df$T_ID))) 

enter image description here

+0

也很好,謝謝。 – Rivka