Excel中圖表如下:
今天折騰了大半天,在ggplot2中,要不是堆積圖要么就是非堆積的,沒法像Excel中做到分組堆積(也許有辦法,但我目前還不知道該如何實現-_-!)
只能是在R中做了個類似的,但問題很多。。。
R中圖形如下:
因為是模擬出來的,還沒法對A,B,C,D進行調整間隔,如果不看對應的Y軸標簽無法很清淅的從圖表上看出誰和誰是一組的
R中代碼如下:
channel <- read.xlsx("c:/myR/channel.xlsx",sheetName="Sheet2",encoding="UTF-8") ggplot(channel, aes(x = as.numeric(interaction(Left,Name)), y = Amount, fill =Type,group=Name)) #把x軸的顯示的內容處理下分組序號 + geom_bar(stat = "identity") + scale_x_continuous(breaks=c(1.5,3.5,5.5,7.5),labels=c("A","B","C","D"))#主要靠這里來定制X軸的顯示內容, +theme( panel.grid.major=element_blank(),panel.grid.minor=element_blank()) +coord_flip() #翻轉如果不加這句則圖像為柱狀圖
數據如下:
Name | Type | Amount | Left |
A | 期初庫存 | 842 | L |
A | 采購 | 96,907 | L |
A | 期末庫存 | 3,250 | R |
A | 銷售 | 94,541 | R |
B | 期初庫存 | 493 | L |
B | 采購 | 58,210 | L |
B | 期末庫存 | 381 | R |
B | 銷售 | 58,321 | R |
C | 期初庫存 | 1,215 | L |
C | 采購 | 56,999 | L |
C | 期末庫存 | 3,373 | R |
C | 銷售 | 54,540 | R |
D | 期初庫存 | 1,293 | L |
D | 采購 | 56,699 | L |
D | 期末庫存 | 6,206 | R |
D | 銷售 | 51,785 | R |
結果並不如意,或許還有好辦法,再研究研究。。。。
---------------------------------------------------------------------------------------------------------------------------------------------
update 2015-07-16
有了另一種解決方案,比上面的效果要好,但只能是柱狀的,不知道怎么樣才能設成條狀的。不過至少圖形看起來能達到分組堆積的效果了
代碼:
ggplot(data = channel2, aes(x = Left, y = Amount, fill = factor(Type) ,order = as.numeric(factor(channel2$Type,levels=c("期初庫存","采購","期末庫存","銷售"))) ))
+ geom_bar(stat = "identity", width = 1, position = "stack" )
+ facet_grid(. ~ Name,scales = "free_x")
+ theme(axis.text.x =element_blank()) #數據還是最上面的數據,對數據按Name進行分片,然后x軸綁定Left字段,再在最后將X軸上顯示的文字取消.
#order = as.numeric(factor(channel2$Type,levels=c("期初庫存","采購","期末庫存","銷售"))) 是設置堆積圖的順序
------------------------------------------------------------------------------------------------------
update
嗯嗯,這次效果終於更進一步,
代碼
ggplot(data = channel2, aes(x =factor(Left,levels=c("R","L")), y = Amount, fill = factor(Type) ,order = as.numeric(factor(channel2$Type,levels=c("期初庫存","采購","期末庫存","銷售"))) )) + geom_bar(stat = "identity", width = 1, position = "stack" ) + theme(axis.text.x =element_blank(),axis.text.y =element_blank()) #不顯示Y,X軸的標簽 +coord_flip() #翻轉 +facet_grid(Name~.) #分片(fact_grid(Name~.) 分片按行顯示如上圖,(facet_grid(.~Name) 分片按列顯示,如上上圖 ^^)