2013-04-10 165 views
1

累積帶狀我想創建一個條形圖顯示與累積值,陰影絲帶:繪製在ggplot [R

require(ggplot2) 
plot_data = data.frame(period=factor(c("t_1", "t_5_to_t_2", "t_8_to_t_2", "t_11_to_t_2", "t_14_to_t_2"), levels=c("t_1", "t_5_to_t_2", "t_8_to_t_2", "t_11_to_t_2", "t_14_to_t_2")), vals = 1:5, ribbon_vals = cumsum(1:5)) 
ggplot(data=plot_data, aes(x=period, y=vals)) + 
geom_bar(stat="identity", colour=c("#6495ED", "#2E8B57", "#2E8B57", "#2E8B57", "#2E8B57")) + 
scale_x_discrete(labels = c('t_1' = expression(t-1), 't_5_to_t_2' = expression(t-5 %->% t-2), 't_8_to_t_2' = expression(t-8 %->% t-2), 't_11_to_t_2' = expression(t-11 %->% t-2), 't_14_to_t_2' = expression(t-14 %->% t-2))) + 
geom_ribbon(aes(x=1:5, y=ribbon_vals)) 

這似乎並沒有工作。什麼是使用geom_ribbon的正確方法?

回答

4

對於geom_ribbon()您應該提供yminymax的值。在這種情況下,ymin是0,而ymaxribbon_valsgeom_ribbon()行應放置在geom_bar()之前。在geom_bar()中使用fill=而不是color=來更改整個欄的顏色(而不僅僅是邊框)。

ggplot(data=plot_data, aes(x=period, y=vals)) + 
    scale_x_discrete(labels = c('t_1' = expression(t-1), 't_5_to_t_2' = expression(t-5 %->% t-2), 't_8_to_t_2' = expression(t-8 %->% t-2), 't_11_to_t_2' = expression(t-11 %->% t-2), 't_14_to_t_2' = expression(t-14 %->% t-2))) + 
    geom_ribbon(aes(x=1:5, ymin=0,ymax=ribbon_vals))+ 
    geom_bar(stat="identity",fill=c("#6495ED", "#2E8B57", "#2E8B57", "#2E8B57", "#2E8B57")) 

enter image description here

+0

優秀!會給這個鏡頭。謝謝。 – Alex 2013-04-10 06:34:57

+0

它如何知道形狀應該是什麼以及如何連接色帶?這很有趣! – Alex 2013-04-10 07:03:29