我有一个看起来像这样但有14000多行和30个独特的'Vessel.Pln'标识符的df;
我正在使用df为每艘船每月按大小创建一个堆积的着陆条形图,为期10年。我希望每隔3个月减少x轴标签的数量,以便它们清晰易读。我已经找到了几个方法来做这个但是我不确定如何在从df矩阵调用条形图时设置轴序列。
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"))
}
要保持使用基数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)]
)
})