如何指定轴标签的数量

时间:2018-04-06 15:35:50

标签: r loops bar-chart axis-labels

我有一个看起来像这样的df但有14000多行和30个独特的' Vessel.Pln'标识符;

我使用df为每艘船每月按尺寸创建一个堆积的着陆条形图,为期10年。我希望每隔3个月减少x轴标签的数量,以便它们清晰易读。我已经找到了一些方法可以做到这一点但是我不确定如何在从df矩阵调用条形图时设置轴序列。

example of axis label overcrowding

    Size.Code   Date    Vessel.Pln  Weight
            2   2011-01-01  BF206   0.174330
            3   2011-01-01  BF206   0.095940
            4   2011-01-01  BF206   0.143910
            5   2011-01-01  BF206   0.407745
            2   2011-02-01  BF206   0.061425
            3   2011-02-01  BF206   0.234000
            5   2011-02-01  BF206   0.327600
            2   2011-05-01  BF206   0.081900
            3   2011-05-01  BF206   0.152100
            4   2011-05-01  BF206   0.444600
            5   2011-05-01  BF206   1.070550
            2   2011-06-01  BF206   0.273780
            3   2011-06-01  BF206   1.965600
            4   2011-06-01  BF206   0.795600
            1   2011-08-01  BF206   0.421200
            2   2011-08-01  BF206   1.329120
            3   2011-08-01  BF206   2.398500
            4   2011-08-01  BF206   2.000700
            5   2011-08-01  BF206   0.649350
            3   2011-10-01  BF206   0.056160

for (a in unique(grade$Vessel.Pln)) {
  df <- grade[grade$Vessel.Pln == a,]
  library(reshape2)
  df2 <- dcast(df,Size.Code~Date,sum)
  library(RColorBrewer)

  barplot(as.matrix(df2),main=a,
    xlim=c(0, ncol(df2) + 20),
    col=brewer.pal(nrow(df2), "Spectral"),
    ylab="Landings (tonnes)",xlab="Month",las=2,cex.names=0.4,
    args.legend=list(
    x=ncol(df2) + 3,
    y=max(colSums(df2)),
    bty = "n"
 )
)
legend(55, 
       legend = c("1", "2","3","4","5"), 
       fill =brewer.pal(nrow(df2), "Spectral"))
}

1 个答案:

答案 0 :(得分:1)

要维持使用基数R barplot,请考虑传递 axisnames = FALSE 并使用axis()重写。下面重写第一个和最后一个日期列之间的每个季度。

另外,考虑使用by,将数据帧拆分为一个或多个因子的函数,为每个不同的 Vessel.Pln 运行图,这样可以避免子集调用和for循环。此外,请务必删除 df2 矩阵的第一列,以便不绘制 Size.Code

by(grade, grade$Vessel.Pln, function(df) {

  df2 <- dcast(df, Size.Code ~ Date,sum, value.var="Weight")

  bp <- barplot(as.matrix(df2[-1]), axisnames = FALSE,
                main = a,
                xlim = c(0, ncol(df2) + 20),
                col = brewer.pal(nrow(df2), "Spectral"),
                ylab = "Landings (tonnes)",xlab="Month",las=2,cex.names=0.4,
                args.legend = list(
                  x = ncol(df2) + 3,
                  y = max(colSums(df2)),
                  bty = "n"
                )
  )

  legend(55, 
         legend = c("1", "2","3","4","5"), 
         fill =brewer.pal(nrow(df2), "Spectral"))

  # REWRITES AXIS FOR YEAR QUARTERS
  axis(1, at = bp[seq(1,ncol(df2[-1]), 3)], 
       labels = names(df2[-1])[seq(1, ncol(df2[-1]), 3)]
  ) 

})

Plot Output