簡體   English   中英

無法將ggplot2中的x軸設置為日期

[英]Cannot set x axis as dates in ggplot2

第一次海報,長期潛伏在R問題上...

我終於被困了48個小時,而我受到了所有人的歡迎。 但希望不會太久!

我嘗試使用ggplot 2繪制一個不規則的時間序列。我希望中斷和標簽僅顯示有數據的日子。

保存日期的變量作為從excel讀取的一個因素開始,我將其轉換為課程日期:

Dataset[,BatchDateCol] <- as.Date(Dataset[,BatchDateCol],format="%m/%d/%y")

(這是一個較大系統的一部分,所以我不能只以不同的方式讀取數據)

我以所需的格式創建標簽的向量:

Date_Vec <- c(history[,BatchDateCol])
Date_Vec <- format(Date_Vec, "%b %d")

然后,我匯總各天的費用以獲取每天的收入:

history <- ddply(Dataset, BatchDateCol, function(z) colMeans(z[RawLocation]))

現在,我要繪制它,為此,我找到了帶有日期和感興趣變量的列:

ProductionDate <- grep(BatchDateCol,colnames(history))
Location <- grep(GGVar, colnames(history))

這是問題開始的地方。 我可以像這樣很好地創建我的情節:

plot2 <- ggplot(history, aes_string(x=history[ProductionDate], y=history[(Location)]))
plot2 + xlab(XAxisName) +ylab(GGVar)+geom_line(aes_string(y=means), linetype="dashed") 
plot2 + geom_point() + geom_smooth(method="lm", formula=y~poly(x,1)) 

但是,當我嘗試將日期添加到x軸時,會出現錯誤,沒有繪圖或沒有breaks + labels。 這兩個命令繪制了正確的圖,但沒有間斷或標簽:

scale_x_continuous(labels=Date_Vec, breaks=c(1:length(history[,BatchDateCol])),
expand=c(.01,0))

scale_x_continuous(labels=Date_Vec, breaks=c(1:length(history[,BatchDateCol])),
limits=c(min(as.numeric(history[,BatchDateCol])),
max(as.numeric(history[,BatchDateCol]))))

此命令繪制正確的中斷和標簽,但不顯示情節(...!)

scale_x_continuous(labels=Date_Vec, 
limits=c(1,length(history[,BatchDateCol])), expand=c(.01,0)) 

當我只用它繪制時:

scale_x_continuous(labels=Date_Vec, expand=c(.01,0)) 

有時可以工作,但是大多數時候我都能得到:

scale_labels.continuous(scale,major)中的錯誤:中斷和標簽的長度不同

如果我沒有在scale_x_continuous中指定標簽,則會得到我想要的日期(1970年以來的天數或其他日期)的數字形式(盡管我不確定它是否在正確的位置繪制),但是我無法確定找出如何修改它。

最后,我嘗試將scale_x_continuous更改為scale_x_date:

plot2 + scale_x_date(expand=c(.01,0))

返回錯誤:(我嘗試在()中放置一些不同的參數)

錯誤:輸入無效:date_trans僅適用於Date類的對象

我嘗試將Dataset [,BatchDateCol]保留為因子或字符向量,但也無法正常工作。

所以。。。我很茫然,感到難以置信的失敗:(

編輯

ProductionDate是在此處定義的帶引號的變量: QC_Process <- function(Dataset, GGVar, XAxisName="TIME SERIES", BatchDateCol, BatchNum=-1, startdate=NULL, enddate=NULL) {...

所以我不能用$來訪問var。 另外,在定義了var之后,我已經立即應用了唯一性(“ history <-unique(history)”)

(這是一個大型R Shiny應用程序的生產代碼,屬於我的雇主,所以我不能在其中發布太多...)

當我使用breaks=(history[,ProductionDate])我得到:

as.Date.numeric(value)中的錯誤:必須提供'origin'

當我使用'breaks =(history [ProductionDate])'時,我得到:

is.finite(x)中的錯誤:類型'list'未實現默認方法

print(history[ProductionDate])返回:

Date.of.Consumption

1 2012-03-24

2 2013-03-11

3 2013-05-10

4 2013-05-11

5 2013-05-13

6 2013-05-16

scale_x_continuous(breaks=unique(history$ProductionDate))應該可以做到(但是我不能完全復制您的代碼,因為我沒有原始的Dataset ,所以我無法測試該解決方案。

通過設置使其正常工作

scale_x_continuous(labels=Date_Vec, Breaks=(as.numeric(history[,ProductionDate])))

仍然不確定為什么可以使用,當我有連續的日期時標簽有時會重疊,但這是進步的!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM