2013-07-15 41 views
-1

我的數據幀,df組個月:如何使柱狀圖ggplot是不同年份

df 
    EffYr EffMo count  dts 
2 2012  1  1 2012-01-01 
3 2012  2  3 2012-02-01 
4 2012  3  1 2012-03-01 
5 2012  5  1 2012-05-01 
6 2012  6  1 2012-06-01 
7 2012  7  2 2012-07-01 
8 2012  8 11 2012-08-01 
9 2012  9 84 2012-09-01 
10 2012 10 184 2012-10-01 
11 2012 11 165 2012-11-01 
12 2012 12 246 2012-12-01 
13 2013  1 414 2013-01-01 
14 2013  2 130 2013-02-01 
15 2013  3 182 2013-03-01 
16 2013  4 261 2013-04-01 
17 2013  5 229 2013-05-01 
18 2013  6 249 2013-06-01 
19 2013  7 330 2013-07-01 
20 2013  8 135 2013-08-01 

df每一行代表一個「月」以來,最早的是2012年1月和最近一次是2013年8月。我想繪製一個條形圖(使用ggplot2),其中每個條形代表一行df,條形高度等於行的count。所以,我應該總共有24個酒吧。

我希望我的x軸被分成12個區間:1月 - 12月,代表同一日曆月的酒吧應位於相同的「月份間隔」。例如,如果df在2011年1月,2012年1月,2013年1月有一行,那麼我的圖表的1月部分應該有3個小節,以便我可以比較我的業務在1月份的業績表現,以用於以後幾年。

感謝

編輯:我想要的東西,看起來像

ggplot(diamonds, aes(cut, fill=cut)) + geom_bar() + 
    facet_grid(. ~ clarity) 

但按月細分。我試圖修改該代碼以適合我的數據,但永遠無法做到。

+1

這聽起來像是從拿訂單外面的餐廳。你試過什麼了? –

+0

@TylerRinker,哈哈。看到我的文章中的編輯。 – Ben

+0

這個問題如何不同於:http://stackoverflow.com/questions/175576​​02/how-do-i-plot-a-bar-graph-in-ggplot-where-my-bins-are-year-months/ 17557895#17557895 –

回答

2

@你要問一些ggplot2問題。我建議你坐下來用一些很好的ggplot2資源,並嘗試這個例子來變得更加熟練。這裏有兩個優秀的資源,我經常使用:

http://docs.ggplot2.org/current/
http://www.cookbook-r.com/Graphs/

現在的解決方案,我認爲你是後:

## dat <- read.table(text=" EffYr EffMo count  dts 
## 2 2012  1  1 2012-01-01 
## 3 2012  2  3 2012-02-01 
## 4 2012  3  1 2012-03-01 
## 5 2012  5  1 2012-05-01 
## 6 2012  6  1 2012-06-01 
## 7 2012  7  2 2012-07-01 
## 8 2012  8 11 2012-08-01 
## 9 2012  9 84 2012-09-01 
## 10 2012 10 184 2012-10-01 
## 11 2012 11 165 2012-11-01 
## 12 2012 12 246 2012-12-01 
## 13 2013  1 414 2013-01-01 
## 14 2013  2 130 2013-02-01 
## 15 2013  3 182 2013-03-01 
## 16 2013  4 261 2013-04-01 
## 17 2013  5 229 2013-05-01 
## 18 2013  6 249 2013-06-01 
## 19 2013  7 330 2013-07-01 
## 20 2013  8 135 2013-08-01", header=TRUE) 

dat$month <- factor(month.name[dat$EffMo], levels = month.name) 
dat$year <- as.factor(dat$EffYr) 

ggplot(dat, aes(month, fill=year)) + geom_bar(aes(weight=count), position="dodge") 

enter image description here

相關問題