celestialgod

split graph with separate x axis

Jul 21st, 2016
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.70 KB | None | 0 0
  1. library(ggplot2)
  2. library(dplyr)
  3. library(grid)
  4. library(gridExtra)
  5.  
  6. if (!file.exists("tmp.zip"))
  7.   download.file("http://seanlahman.com/files/database/baseballdatabank-master_2016-03-02.zip",
  8.                 "tmp.zip")
  9. teamStat <- read.csv(unz(sprintf("%s/tmp.zip", getwd()),
  10.                        "baseballdatabank-master/core/Teams.csv"),
  11.                      header = TRUE, stringsAsFactors = FALSE) %>% tbl_df %>%
  12.   filter(yearID == 2015)
  13.  
  14. ggplotColours <- function(n = 6, h = c(0, 360) + 15){
  15.   if ((diff(h) %% 360) < 1) h[2] <- h[2] - 360/n
  16.   hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
  17. }
  18. cols <- ggplotColours(2)
  19.  
  20. combns_lg_div <- distinct(teamStat, lgID, divID) %>% as.matrix
  21. graphs <- apply(combns_lg_div, 1, function(v){
  22.   cols_fill <- ifelse(v[1] == "AL", cols[1], cols[2])
  23.   teamStat %>% filter(lgID == v[1], divID == v[2]) %>%
  24.     ggplot(aes(x = teamID, y = W)) +
  25.     geom_bar(position="stack",stat="identity", fill = cols_fill)+
  26.     geom_text(aes(label= W), vjust = 1.5, colour = "black",
  27.               position = position_dodge(0.9), size=5) +
  28.     labs(x = "隊伍", y = "勝場數")
  29. })
  30.  
  31. get_legend <- function(myggplot){
  32.   tmp <- ggplot_gtable(ggplot_build(myggplot))
  33.   leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  34.   legend <- tmp$grobs[[leg]]
  35.   return(legend)
  36. }
  37. getLegendGraph <- ggplot(teamStat ,aes(x=teamID, y=W, fill=lgID)) +
  38.   geom_bar(position="stack",stat="identity")
  39.  
  40. grid.arrange(graphs[[1]], graphs[[2]], graphs[[3]], get_legend(getLegendGraph),
  41.              graphs[[4]], graphs[[5]], graphs[[6]], ncol = 4, nrow = 2,
  42.              layout_matrix = cbind(c(1, 5), c(2, 6), c(3, 7), 4),
  43.              widths = c(2.3, 2.3, 2.3, 0.8))
Advertisement
Add Comment
Please, Sign In to add comment