2016-06-20 66 views
0

IM在這個DF工作:刻面跳過值x軸

library("ggplot2") 
library("reshape2") 
library("tidyr") 
library("scales") 
library("dplyr") 


Col0 <- c("AA", "BB", "CC", "DD","EE","FF") 
D01012015 <- c(2,2,2,6,1,NA) 
D02012015 <- c(2,2,2,1,3,1) 
D03012015 <- c(2,2,3,4,6,4) 
D04012015 <- c(2,2,3,1,2,4) 
D05012015 <- c(2,1,1,1,1,0) 
D06012015 <- c(2,4,2,5,4,9) 
D07012015 <- c(2,4,2,5,4,1) 
D08012015 <- c(2,2,3,4,5,3) 
D09012015 <- c(1,3,3,2,2,1) 
D10012015 <- c(1,3,3,2,2,1) 
D11012015 <- c(1,3,3,2,4,1) 
D12012015 <- c(1,3,3,4,2,1) 
D13012015 <- c(1,3,5,2,2,1) 
D14012015 <- c(1,3,3,7,2,1) 
D15012015 <- c(1,3,3,7,2,7) 

df<-data.frame(Col0,D01012015,D02012015,D03012015,D04012015,D05012015,D06012015,D07012015,D08012015,D09012015,D10012015,D11012015, 
       D12012015,D13012015,D14012015,D15012015) 

我知道,通常情況下,如果我想在x軸上打印每週值我應該創建這個ggplot功能:

f<-melt(df,id =c("Col0")) 
f$date<-as.Date(f$variable, format="D%d%m%Y") 
pl<- ggplot(f, aes(date, value, fill=Col0))+ geom_line(aes(color=Col0,group=Col0))+ scale_x_date(breaks = date_breaks("1 week")) 

我的問題是,我要創建相同的x軸值,使用此功能:

plotfun = function(data) { 

    xval<-"dates" 
    column<- names(data)[1] 
    data %>% 
    gather_(xval, "Val", select_vars_(names(.), 
             names(.), 
             exclude = column)) %>% 
    ggplot(aes_string(xval, "Val", group = column, col = column)) + 
    facet_grid(as.formula(paste(column, "~."))) + 
    geom_line() 
} 

plotfun(df) 

我不知道如何轉換日期s的x值與收集以及如何跳轉值如以前的ggplot函數

+0

請做一個[可重現的例子](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example);您的當前代碼不會在新環境中運行,因爲並非所有程序包都已加載。 – Heroka

+0

@Heroka我編輯的問題添加庫 – juse

回答

1

你不能只是把一個mutate陳述嗎?

plotfun <- function(data) { 

    xval <- "dates" 
    column <- names(data)[1] 
    data %>% 
    gather_(xval, "Val", select_vars_(names(.), 
             names(.), 
             exclude = column)) %>% 
    mutate(dates = as.Date(f$variable, format = "D%d%m%Y")) %>% 
    ggplot(aes_string(xval, "Val", group = column, col = column)) + 
    facet_grid(as.formula(paste(column, "~."))) + 
    geom_line() 
} 

plotfun(df) 
+0

它的工作完美,謝謝 – juse