2017-11-11 215 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