問題描述
在 scale_x_continuous 中使用日期與中斷 (Using date in scale_x_continuous with breaks)
我正在嘗試替換使用 step 創建的 x 軸值,即值 1:50。我可以使用 scale_x_continuous 輕鬆替換這些,但是當我使用休息時,我得到以下錯誤。我不能在我正在使用的繪圖函數中使用日期和時間,所以尋找一種解決方法來獲取我的軸上的日期
Date = c( "2018‑10‑18 00:00:00 BST", "2018‑10‑18 00:10:00 BST", "2018‑10‑18 00:20:00 BST", "2018‑10‑18 00:30:00 BST", "2018‑10‑18 00:40:00 BST", "2018‑10‑18 00:50:00 BST",
"2018‑10‑18 01:00:00 BST", "2018‑10‑18 01:10:00 BST", "2018‑10‑18 01:20:00 BST", "2018‑10‑18 01:30:00 BST", "2018‑10‑18 01:40:00 BST", "2018‑10‑18 01:50:00 BST",
"2018‑10‑18 02:00:00 BST", "2018‑10‑18 02:10:00 BST", "2018‑10‑18 02:20:00 BST", "2018‑10‑18 02:30:00 BST", "2018‑10‑18 02:40:00 BST", "2018‑10‑18 02:50:00 BST",
"2018‑10‑18 03:00:00 BST", "2018‑10‑18 03:10:00 BST", "2018‑10‑18 03:20:00 BST", "2018‑10‑18 03:30:00 BST", "2018‑10‑18 03:40:00 BST", "2018‑10‑18 03:50:00 BST",
"2018‑10‑18 04:00:00 BST", "2018‑10‑18 04:10:00 BST", "2018‑10‑18 04:20:00 BST", "2018‑10‑18 04:30:00 BST", "2018‑10‑18 04:40:00 BST", "2018‑10‑18 04:50:00 BST",
"2018‑10‑18 05:00:00 BST", "2018‑10‑18 05:10:00 BST", "2018‑10‑18 05:20:00 BST", "2018‑10‑18 05:30:00 BST", "2018‑10‑18 05:40:00 BST", "2018‑10‑18 05:50:00 BST",
"2018‑10‑18 06:00:00 BST", "2018‑10‑18 06:10:00 BST", "2018‑10‑18 06:20:00 BST", "2018‑10‑18 06:30:00 BST", "2018‑10‑18 06:40:00 BST", "2018‑10‑18 06:50:00 BST",
"2018‑10‑18 07:00:00 BST", "2018‑10‑18 07:10:00 BST", "2018‑10‑18 07:20:00 BST", "2018‑10‑18 07:30:00 BST", "2018‑10‑18 07:40:00 BST", "2018‑10‑18 07:50:00 BST",
"2018‑10‑18 08:00:00 BST", "2018‑10‑18 08:10:00 BST")
Step <‑ c(1:50)
Value <‑ runif(50,0,10)
Final <‑ data.frame(Step, Value)
ggplot(Final, aes(x = Step, y = Value)) +
geom_line(size = 1) +
geom_point() +
scale_x_continuous(labels=Date,breaks = seq(1, 50)) #works
scale_x_continuous(labels=Date,breaks = seq(1, 50,by=10)) #doesntwork
Error: `breaks` and `labels` must have the same length
參考解法
方法 1:
You need to subset your lables (Dates in your case) too:
ggplot(Final, aes(x = Step, y = Value)) +
geom_line(size = 1) +
geom_point() +
scale_x_continuous(labels=Date[seq(1, 50,by=10)],
breaks = seq(1, 50,by=10))
方法 2:
I would drop creating Step
and just use your dates directly as the X‑value in your plot. The reason R won't subset is because it considers your 50 dates as 50 strings. Convert to a datettime class and manipulate it with scale_x_datetime()
:
Value <‑ runif(50,0,10)
Final <‑ data.frame(Value, Date)
Final$Date = as.POSIXct(Date)
ggplot(Final, aes(x = Date, y = Value, group = 1)) +
geom_line(size = 1) +
geom_point() +
scale_x_datetime(date_breaks = "2 hours", date_labels = "%H:%M")
(by HaydenC、StupidWolf、Ederi)