堆积的条形图R(多个变量)

时间:2015-10-07 21:55:26

标签: r bar-chart

尝试生成堆积的条形图(类似下图,除了多年和堆积的条形图)。理想情况下,x轴将是几个月J,F,M ......重复(实现行名称不能复制,但我想知道是否有一种方法来标记轴然后按年分组)并且会有2个y轴 - 与示例相同。我试图将2 *'RainAvg'列作为右侧轴上的堆叠条形图,然后将2 *'GRACEAnom'列作为与左轴相关的2条线。不确定从哪里开始....任何帮助一如既往的赞赏 - 希望这是明确的。我在图片下面添加了我的前几行数据: enter image description here

> head(Figures, 34)
   DecimDate GRACEAnomLVB RainAvgLVB GRACEAnomVNB RainAvgVNB
1   2003.000  13.46956583   5.749109   6.15705017   3.478762
2   2003.083   6.31473051   5.331211   0.97906465   2.873399
3   2003.167   3.63883171  10.363173   0.77220028   8.090037
4   2003.250   6.49458212  17.210327   1.24673188  17.405001
5   2003.333  11.33909662  14.840302   5.56158736  15.673977
6   2003.417   9.38271799   7.536387   6.00824271   9.961779
7   2003.500   7.42633936   7.322593   6.45489806   9.617705
8   2003.583   3.60612356  11.447746   5.60098976  15.430943
9   2003.667   3.44546767   7.968092   6.63687748   8.056800
10  2003.750   2.75612873   8.769927   5.22673658   8.333266
11  2003.833   5.30475366   9.782655   6.91241363   9.305419
12  2003.917   8.68239955   7.474251   7.37673817   5.731811
13  2004.000   5.48150209   9.109684   4.04360382   5.772269
14  2004.083   2.62570392   6.976879  -0.71817402   3.780555
15  2004.167   1.45723630  10.559618  -2.23807975   6.471265
16  2004.250   5.98037042  17.895779   0.04639658  17.677118
17  2004.333   7.35279067   7.203534   3.23732162   8.284600
18  2004.417   1.41878133   4.536058   0.41008077   6.321057
19  2004.500  -0.89443672   5.439750   0.09167621   7.704055
20  2004.583  -3.98526800   9.248759  -0.22851368  12.973643
21  2004.667  -4.91880694  12.214854  -0.30143818  12.626995
22  2004.750  -4.13842871  10.903502   1.08566462  11.491835
23  2004.833   1.04833693  15.731056   4.50875694  12.300916
24  2004.917   2.93758790   8.431368   3.10471313   3.997466

......依此类推至2012年12月。

1 个答案:

答案 0 :(得分:3)

我对你的图表描述中的几个项目不太清楚,例如你是在寻找所有年份的一个图表还是每年一个图表,但以下代码可能会帮助你开始。基本思想是绘制条形图,然后重新缩放线图的绘图窗口。根据需要添加图表标题和标签。

  org_mar <- par()$mar
  par(mar=c(5,4,4,5)+.1)
  Figures <- as.matrix(Figures)
  nrow_F <- nrow(Figures)
  x_labs <- cbind(1:nrow_F,c("J","F","M","A","M","J","J","A","S","O","N","D") )[,2]
# make bar chart
  barplot(t(Figures[,c("RainAvgLVB","RainAvgVNB")]), yaxt="n", names.arg=x_labs, 
          xlab = "Monthly", font.lab=2, xlim= 1.2*c(1,nrow_F)-.5)
  axis(side=4)
  mtext("Mean Monthly Rainfall (mm)", side=4, line=2.5, font=2)
  abline(h=0)
# rescale the plot window and draw the line plots
  plot.window(xlim=c(1,nrow_F), ylim=range(Figures[,c("GRACEAnomLVB","GRACEAnomVNB")]))
  axis(side=2)
  mtext("Water Storage Anomalay (cm)", side=2, line=2.5, font=2)
  abline(v=par()$usr[1])
  lines( Figures[,2], col="black", lty=1, lwd=2)
  lines( Figures[,4], col="blue",  lty=2, lwd=2)
  par(mar=org_mar)

这应该制作如下图表:

enter image description here