分层区域图与ggplot 2

时间:2014-03-29 23:30:55

标签: r ggplot2

我有兴趣为巴西GDP创建一个区域图,根据GDP组成分层。我有以下数据框:

> head(data)
   Quarter      C     G       I    NX
1   1995.I 100057 35636 24624.0 -3387
2  1995.II 104893 35651 33928.0 -3691
3 1995.III 115704 36905 29423.0 -1772
4  1995.IV 120058 40242 39233.0 -1863
5   1996.I 105639 33202 26552.0  -523
6  1996.II 108432 35326 34160.2 -1807

我设法通过以下方式重新组织它:

> head(data.new) 
     Quarter components  reals id
1.C   1995.I          C 100057  1
2.C  1995.II          C 104893  2
3.C 1995.III          C 115704  3
4.C  1995.IV          C 120058  4
5.C   1996.I          C 105639  5
6.C  1996.II          C 108432  6

然后我使用以下命令以使用gplot2绘图:

  graph1 = ggplot(data.new, aes(x = Quarter, y = reals, fill = components)) + 
  geom_area(position = 'stack') +
  labs(x = "Quarter", 
       y = "$R (millions)",
       title = "Composition of GDP for Brazil")

然而,在打印graph1时,我会得到一个带有正确的x和y轴和图例的图,但没有绘制区域。

有人可以指出我的错误吗?

1 个答案:

答案 0 :(得分:0)

像你这样的东西正在寻找? (它与我所说的没什么不同):

dat <- structure(list(Quarter = structure(1:6, .Label = c("1995.I", "1995.II", "1995.III", "1995.IV", "1996.I", "1996.II"), class = "factor"), 
                      C = c(100057L, 104893L, 115704L, 120058L, 105639L, 108432L), 
                      G = c(35636L, 35651L, 36905L, 40242L, 33202L, 35326L), 
                      I = c(24624, 33928, 29423, 39233, 26552, 34160.2), 
                      NX = c(-3387L, -3691L, -1772L, -1863L, -523L, -1807L)), 
                 .Names = c("Quarter", "C", "G", "I", "NX"), class = "data.frame", row.names = c(NA, -6L))

dat.m <- melt(dat, id.vars=c("Quarter"))

gg <- ggplot(dat.m, aes(x=Quarter, y=value , group=variable, fill=variable))
gg <- gg + geom_area(position="stack")
gg <- gg + labs(x = "Quarter", y = "$R (millions)", title = "Composition of GDP for Brazil")
gg <- gg + theme_bw()
gg

plot