概述
将df 转换成一个宽矩阵——df$Month 中的每个值一列,每个非df$Month 列一列——在barplot() 内部使用它之前。
由于df$Month 以缩写的月-年格式给出,zoo 包中的as.yearmon() 函数用于在绘图之前按时间顺序对矩阵进行排序。
可重现的示例
# load necessary packages
library( zoo )
# load data
df <-
read.table(
text = "Month Fig1 Fig2
Mar-17 10 12
Feb-17 25 18
Jan-17 10 15
Dec-16 11 18
Nov-16 10 15"
, header = TRUE
, stringsAsFactors = FALSE
)
# create complementary color scheme
color.scheme <- c( "#18A4D2", "#D24618" )
# store non-Month column indices
non.month.column.condition <-
which( !colnames( df ) %in% "Month" )
# transfrom Month to a
# yearmon class using the zoo package
df$Month <-
as.yearmon( x = df$Month, format = "%b-%y" )
# reorder the data frame by
# chronological order
df <-
df[ order( df$Month ), ]
# transform df
# to wide matrix
# one column for each value in df$Month
month.values.by.fig <-
lapply(
X = df[ , non.month.column.condition ]
, FUN = function( i )
tapply(
X = i
, INDEX = df$Month
, FUN = function( j )
j
)
)
# collapse values into one matrix
month.values.by.fig <-
do.call(
what = "rbind"
, args = month.values.by.fig
)
# plot and save the results
png(
filename = "fig_value_by_month.png"
, units = "px"
, height = 1600
, width = 2400
, res = 300
)
barplot(
height = month.values.by.fig
, beside = TRUE
, col = color.scheme
, border = NA
, legend.text = TRUE
, args.legend = list(
x = "topleft"
, bty = "n"
, border = NA
)
, las = 1
, ylim = c( 0, 30 )
, xlab = "Month-Year"
, ylab = "Values"
, main = "Values Over Time, by Figure Type"
)
# shut down plot device
dev.off()
# end of script #