2017-03-18 54 views
0

我有一名運動員的數據以及他們在每場比賽中每場比賽的位置。每季度最多20分鐘。根據因素改變背景,不能在ggplot2中工作

我想繪製每個位置花費的時間,由這個球員,並根據位置改變顏色。我的問題是similar to this one,所以我使用ggplot2中的geom_rect代碼。

我的數據的一個例子是:

# Sample data.frame 
df <- data.frame(Time=c(0, 5.35, 19.26, 23.32, 
          9.08, 13.11, 0, 0, 
          7.36, 2.51, 6.44, 22.47, 
          0, 24.38, 11.36), 
        Athlete = c('Paul', 'Paul', 'Paul', 'Paul', 
           'Paul', 'Paul', 'Paul','Paul', 
           'Paul', 'Paul', 'Paul','Paul', 
           'Paul', 'Paul', 'Paul'), 
        Quarter = c('Q1', 'Q1', 'Q1', 'Q1', 
           'Q2', 'Q2', 'Q2', 'Q3', 
           'Q3', 'Q3', 'Q4', 'Q4', 
           'Q4', 'Q4', 'Q4'), 
        Position = c('Bench','Defender','Bench','Defender', 
           'Bench','Defender','Defender','Defender', 
           'Defender','Bench','Bench','Bench', 
           'Defender', 'Defender', 'Defender')) 

我在他們的排名值50增加的比賽,並繪製這個隨着時間的推移。我用它來做到這一點的代碼是:

# Add in necessary column 
df$Value <- c(50) 
    # Plot 
    ggplot(df, aes(x = Time, y = Value)) + 
     geom_rect(aes(NULL, NULL, 
        xmin=Time, xmax=30, 
        ymin=0, ymax=50, 
        fill = Position)) + 
     scale_y_continuous(expand = c(0, 0), limits = c(0, 50)) + 
     scale_x_continuous(expand = c(0, 0), limits = c(0, 30)) + 
     theme_classic() + 
     theme(legend.position = "none", 
      axis.title.x = element_blank(), 
      axis.title.y = element_blank(), 
      axis.text.y = element_blank(), 
      axis.text.x = element_text(face = "bold", colour = "black", size = 10), 
      axis.ticks.y = element_blank(), 
      axis.line.y = element_blank(), 
      panel.spacing = unit(1.5, "lines"), 
      strip.text = element_text(color = "black", size = 12, face = "bold")) + 
     facet_wrap(~ Quarter, nrow = 1) 

但是劇情不顯示當運動員季度2和4例如在被換下場正確的顏色,保羅開始爲Q2一名後衛,然後去在9.08替補出場,然後在13.11分鐘出場作爲防守球員出場。 Q2不是每種顏色都顯示這段時間,而是Q2全是藍色。

我輸入了錯誤代碼geom_rect

+0

因爲您設置了xmax = 30,所以您的矩形被覆蓋。你可以用alpha = 0.5來看它。 – baptiste

+0

謝謝,我該如何設置xmax以確保我看到這個正確? – user2716568

+0

有太多我不明白的數據讓我回答。我認爲這是某種足球術語,時間和宿舍的意義等等。 – baptiste

回答

0

我可以通過簡單地重新排序數據幀以便時間順序來獲得所需的繪圖。我使用以下代碼創建了所需的繪圖:

# Order data.frame 
attach(df) 
df <- df[order(Athlete, Quarter, Time),] 
# Re-plot 
ggplot(df, aes(x = Time, y = Value)) + 
    geom_rect(aes(NULL, NULL, 
       xmin=Time, xmax=30, 
       ymin=0, ymax=50, 
       fill = Position)) + 
    scale_y_continuous(expand = c(0, 0), limits = c(0, 50)) + 
    scale_x_continuous(expand = c(0, 0), limits = c(0, 30)) + 
    theme_classic() + 
    theme(legend.position = "bottom", 
     axis.title.x = element_blank(), 
     axis.title.y = element_blank(), 
     axis.text.y = element_blank(), 
     axis.text.x = element_text(face = "bold", colour = "black", size = 10), 
     axis.ticks.y = element_blank(), 
     axis.line.y = element_blank(), 
     panel.spacing = unit(1.5, "lines"), 
     strip.text = element_text(color = "black", size = 12, face = "bold")) + 
    facet_wrap(~ Quarter, nrow = 1)