2019年8月28日水曜日

ggplot() data.frame() geom="bar" ggplot2を使用した棒グラフ その2


w <- to.monthly(SP5)[,4][2:836]/as.vector(to.monthly(SP5)[,4][1:835])
w <- w-1
# will use "c(last(seq(1,12,1),month(index(last(apply.monthly(SP5[,4],sd)))) ),head(seq(1,12,1),12-month(index(last(apply.monthly(SP5[,4],sd)))) ))" in the future
#
ggplot(data.frame(data=apply(matrix(last(w,floor(length(w)/12)*12),nrow=12),1,mean)[c(5,6,7,8,9,10,11,12,1,2,3,4)],mon=c("01jan","02feb","03mar","04apr","05may","06jun","07jul","08aug","09sep","10oct","11nov","12dec")),aes(x=mon,y=data,fill =mon)) +
scale_x_discrete(label=c("jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec")) + #x-axis label
stat_summary(fun.y=NULL,geom="bar") + # speciy "bar" graph
theme(legend.position = 'none')  # erase legend


# the final version

use "c(last(seq(1,12,1),month(index(last(apply.monthly(SP5[,4],sd)))) ),head(seq(1,12,1),12-month(index(last(apply.monthly(SP5[,4],sd)))) ))"
# to calculate the order of months like "c(5,6,7,8,9,10,11,12,1,2,3,4)" for August.
#
len <- length(index(to.monthly(SP5)))
w <- to.monthly(SP5)[,4][2:len]/as.vector(to.monthly(SP5)[,4][1:(len-1)])
w <- w-1
# need factor() to set descrete index, other wise continus/gradation will be used as color scheme.
#
df <- data.frame(data=apply(matrix(last(w,floor(length(w)/12)*12),nrow=12),1,mean)[  c(last(seq(1,12,1),month(index(last(apply.monthly(SP5[,4],sd)))) ),head(seq(1,12,1),12-month(index(last(apply.monthly(SP5[,4],sd)))) )) ],mon=factor(seq(1,12,1)))
p <- ggplot(df, aes(x=mon,y=data,fill =mon)) 
p <- p + scale_x_discrete(label=c("jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"))  #x-axis label
p <- p + geom_bar(stat = "identity") # need identity to draw value itself. 
p <- p + theme(legend.position = 'none')  # erase legend
plot(p)





0 件のコメント: