在ggplot R中绘制累积色带

时间:2013-04-10 06:25:57

标签: r plot ggplot2

我想用阴影带创建一个显示累积值的条形图:

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的正确方法是什么?

1 个答案:

答案 0 :(得分:4)

对于geom_ribbon(),您应该提供yminymax值。在这种情况下,ymin为0,ymaxribbon_valsgeom_ribbon()行应放在geom_bar()之前。在fill=中使用color=代替geom_bar()来更改整个条形的颜色(不仅仅是边框)。

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