2017-11-11 168 views
1

我有一個數據框只列出十月到四月的月份。當我將這些數據繪製在折線圖上時,它也包含未使用的月份。我只想顯示數據中列出的月份,因此圖上沒有未使用的空間。在ggplot上刪除未使用的月份

我使用的情節代碼

gplot(df,aes(GAME_DATE,DEF_RATING)) + 
    geom_line(aes(y=rollmean(df$DEF_RATING,9, na.pad = TRUE))) + 
    geom_line(aes(y=rollmean(df$OFF_RATING,9,na.pad = TRUE)),color='steelblue') 

enter image description here

的樣本數據

GAME_DATE OFF_RATING DEF_RATING 
     <dttm>  <dbl>  <dbl> 
1 2017-04-12  106.1  113.1 
2 2017-04-10  107.1  100.8 
3 2017-04-08  104.4  105.1 
4 2017-04-06  116.1  105.9 
5 2017-04-04  116.9  116.0 
+0

請你能提供一些示例數據?查看https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example以獲取幫助 – Phil

+0

在'aes'內重新聲明數據框名稱是不必要的也是不可取的。使用純粹的變量名稱:'geom_line(aes(y = rollmean(DEF_RATING,9,na.pad = TRUE)))'。 – eipi10

+0

@Phil添加了示例數據 – jhaywoo8

回答

0

您可以嘗試劃定x軸與 「scale_x_date()」 你的禮物像這樣的日期:

gplot(df,aes(GAME_DATE,DEF_RATING)) + 
geom_line(aes(y=rollmean(df$DEF_RATING,9, na.pad = TRUE))) + 
geom_line(aes(y=rollmean(df$OFF_RATING,9,na.pad = TRUE)),color='steelblue') +  
scale_x_date(date_labels="%b",breaks=seq(min(df$GAME_DATE),max(df$GAME_DATE), "1 month")) 
1

ggplot2不允許損壞軸,因爲這些軸可能會引起誤解。但是,如果您仍想繼續此操作,則可以使用切面來模擬斷開的軸。要做到這一點,創建一個分組變量來標記每個「島」,其中數據出現在唯一的組代碼中,然後由這些組代碼分面。

此外,繪圖前應將數據轉換爲長格式,以便您可以通過一次調用geom_line獲得兩條單獨的彩色線條。將列映射到aes內部的顏色也會自動生成圖例。

下面是用假數據爲例:

library(tidyverse) 

# Fake data 
set.seed(2) 
dat = data.frame(x=1950:2000, 
       y1=c(cumsum(rnorm(30)), rep(NA,10), cumsum(rnorm(11))), 
       y2=c(cumsum(rnorm(30)), rep(NA,10), cumsum(rnorm(11)))) 

dat %>% 
    # Convert to long format 
    gather(key, value, y1:y2) %>% 
    # Add the grouping variable 
    group_by(key) %>% 
    mutate(group=c(0, cumsum(diff(as.integer(is.na(value)))!=0))) %>% 
    # Remove missing values 
    filter(!is.na(value)) %>% 
    ggplot(aes(x, value, colour=key)) + 
    geom_line() + 
    scale_x_continuous(breaks=seq(1950,2000,10), expand=c(0,0.1)) + 
    facet_grid(. ~ group, scales="free_x", space="free_x") + 
    theme(strip.background=element_blank(), 
      strip.text=element_blank()) 

enter image description here

+0

您如何使用我的樣本數據來做到這一點? – jhaywoo8

相關問題