2017-07-19 47 views
0

當前使用ggplot2並對此進行縮放,但最好顯示日期範圍+/- 1年(例如)。我不應該對這些日期進行硬編碼,因爲它效率不高。用R尺度限制以編程方式顯示日期範圍

library(scales) #date time scales 
library(ggplot2) # Visualization 

ggplot(dataset,aes(x=datetime_start, y=dataset$Product, color=Stage, order = - as.numeric(Stage))) + 
geom_segment(aes(x=From,xend=To,yend=dataset$Product), size=10) + 
scale_x_datetime(
breaks = date_breaks("1 month"), 
labels=date_format("%b%y"), 
limits = c(
     as.POSIXct("2016-03-01"), 
     as.POSIXct("2018-02-01") 
) 
) + 

回答

1

擴大規模:

library(ggplot2) 
df <- data.frame(x = seq(Sys.Date()-lubridate::years(2), Sys.Date(), by="3 month")) 
df$y <- 1:nrow(df) 
p <- ggplot(df, aes(x, y)) + geom_line() 
p + scale_x_date(expand = c(0, 365)) 
+0

看起來你還需要lubridate包,不是嗎? –

+0

這看起來不錯,只是混淆了它如何適合我當前的代碼。試圖讓它工作,但不能。你能否幫助澄清它如何適合我目前的狀況? –

+0

@JaredPace請編輯你的文章,並提供一個[最小可重現的例子](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#answer-5963610)你得到了,就像R標籤所示(懸停在它上面)。然後你可以看到你現在有什麼,以及爲什麼上述不起作用。 (我想這是因爲我使用日期和時間,所以你需要做60 * 60 * 24 * 365(秒*分鐘*小時*每年,而不是僅僅365天)。 – lukeA