R で ヒストグラム ~少年サッカー データ分析~
open color を参考に色を指定する
yeun.github.io
RED_5 <- "#ff6b6b" PINK_5 <- "#f06595" GRAPE_5 <- "#cc5de8" VIOLET_5 <- "#845ef7" INDIGO_5 <- "#5c7cfa" BLUE_5 <- "#339af0" CYAN_5 <- "#22b8cf" TEAL_5 <- "#20c997" GREEN_5 <- "#51cf66" LIME_5 <- "#94d82d" YELLOW_5 <- "#fcc419" ORANGE_5 <- "#ff922b"
同じような処理を繰り返すので、関数として定義しておく
my_hist <- function(d, aItem, aBinWidth, aTitle, aXlab, aYlab) { g <- ggplot(d) g <- g + geom_histogram( aes( x=aItem, y=..count.., colour= d$"勝敗", fill=d$"勝敗" ), binwidth=aBinWidth, alpha=0.2, position="identity" ) g <- g + labs(title=aTitle) g <- g + xlab(aXlab) g <- g + ylab(aYlab) g <- g + labs(colour="凡例", fill="凡例") g <- g + theme_bw( base_size=12, base_family="HGKAI" ) g <- g + theme( legend.position="right", plot.title=element_text(hjust=0.5), axis.text=element_text(family="COURIER", size=10) ) g <- g + scale_fill_manual( values=c(GREEN_5, BLUE_5, PINK_5), breaks=c("勝","負","引き分け"), labels=c("勝","負","引き分け") ) g <- g + scale_colour_manual( values=c(GREEN_5, BLUE_5, PINK_5), breaks=c("勝","負","引き分け"), labels=c("勝","負","引き分け") ) return (g) }
さまざまな変量のヒストグラムを作成
# 10分あたりのボールタッチ回数 g1 <- my_hist( d, d$"自チーム.10分あたりのTOUCH数", 5, "タッチ回数", "10分あたりのボールタッチ回数", "試合数" ) g1 # 10分あたりのボールキープ回数 g2 <- my_hist( d, d$"自チーム.10分あたりのKEEP数", 5, "キープ回数", "10分あたりのボールキープ回数", "試合数" ) g2 # 10分あたりのシュート数 g3 <- my_hist( d, d$"自チーム.10分あたりのSHOT", 0.5, "シュート数", "10分あたりのシュート数", "試合数" ) g3 # 10分あたりの被シュート数 g4 <- my_hist( d, d$"相手チーム.10分あたりのSHOT", 0.5, "被シュート数", "10分あたりの被シュート数", "試合数" ) g4 # 10分あたりの得点 g5 <- my_hist( d, d$"自チーム.10分あたりの得点", 0.25, "得点", "10分あたりの10分あたりの得点", "試合数" ) g5 # 10分あたりの失点 g6 <- my_hist( d, d$"自チーム.10分あたりの失点", 0.25, "失点", "10分あたりの10分あたりの失点", "試合数" ) g6
ならべて表示
grid.arrange(g1, g2, g3, g4, g5, g6, ncol=2)
凡例がいちいちうるさいので、頑張ってみる
# いったん凡例を下に表示するバージョンの graphic pbject を作る g1_grob <- ggplotGrob(g1 + theme(legend.position="bottom")) # その object から 凡例のパーツの index を取得する legend_idx <- grep("guide-box", g1_grob$layout$name) # その object から 凡例のパーツを取得する legend <- g1_grob[["grobs"]][[legend_idx]] # 凡例を表示しないバージョンと、凡例を並べて表示する grid.arrange( g1 + theme(legend.position="none"), g2 + theme(legend.position="none"), g3 + theme(legend.position="none"), g4 + theme(legend.position="none"), g5 + theme(legend.position="none"), g6 + theme(legend.position="none"), legend, layout_matrix = rbind(c(1,2), c(3,4), c(5,6), c(7,7)), widths = unit.c(unit(0.5, "npc"),unit(0.5, "npc")), heights = unit.c(unit(0.31, "npc"),unit(0.31, "npc"),unit(0.31, "npc"),unit(0.07, "npc")) )