使用 scale_x_datetime 和时间数据设置限制
Setting limits with scale_x_datetime and time data
我想为仅包含时间(无日期)的时间序列数据图设置 x 轴的界限。我的限制是:
lims <- strptime(c("03:00","16:00"), format = "%H:%M")
我的 ggplot 打印正常,但是当我将它添加到 scale_x_datetime
scale_x_datetime(limits = lims)
我得到Error: Invalid input: time_trans works with objects of class POSIXct only
完全可重现的示例由 How to create a time scatterplot with R?
提供
dates <- as.POSIXct(as.Date("2011/01/01") + sample(0:365, 100, replace=TRUE))
times <- as.POSIXct(runif(100, 0, 24*60*60), origin="2011/01/01")
df <- data.frame(
dates = dates,
times = times
)
lims <- strptime(c("04:00","16:00"), format = "%H:%M")
library(scales)
library(ggplot2)
ggplot(df, aes(x=dates, y=times)) +
geom_point() +
scale_y_datetime(limits = lims, breaks=date_breaks("4 hour"), labels=date_format("%H:%M")) +
theme(axis.text.x=element_text(angle=90))
错误消息说您应该在 lims
上使用 as.POSIXct
。
您还需要在 lims
中添加日期(年、月和日),因为默认情况下它是 `2015,这是不允许的。
lims <- as.POSIXct(strptime(c("2011-01-01 03:00","2011-01-01 16:00"), format = "%Y-%m-%d %H:%M"))
ggplot(df, aes(x=dates, y=times)) +
geom_point() +
scale_y_datetime(limits =lims, breaks=date_breaks("4 hour"), labels=date_format("%H:%M"))+
theme(axis.text.x=element_text(angle=90))
我想为仅包含时间(无日期)的时间序列数据图设置 x 轴的界限。我的限制是:
lims <- strptime(c("03:00","16:00"), format = "%H:%M")
我的 ggplot 打印正常,但是当我将它添加到 scale_x_datetime
scale_x_datetime(limits = lims)
我得到Error: Invalid input: time_trans works with objects of class POSIXct only
完全可重现的示例由 How to create a time scatterplot with R?
提供dates <- as.POSIXct(as.Date("2011/01/01") + sample(0:365, 100, replace=TRUE))
times <- as.POSIXct(runif(100, 0, 24*60*60), origin="2011/01/01")
df <- data.frame(
dates = dates,
times = times
)
lims <- strptime(c("04:00","16:00"), format = "%H:%M")
library(scales)
library(ggplot2)
ggplot(df, aes(x=dates, y=times)) +
geom_point() +
scale_y_datetime(limits = lims, breaks=date_breaks("4 hour"), labels=date_format("%H:%M")) +
theme(axis.text.x=element_text(angle=90))
错误消息说您应该在 lims
上使用 as.POSIXct
。
您还需要在 lims
中添加日期(年、月和日),因为默认情况下它是 `2015,这是不允许的。
lims <- as.POSIXct(strptime(c("2011-01-01 03:00","2011-01-01 16:00"), format = "%Y-%m-%d %H:%M"))
ggplot(df, aes(x=dates, y=times)) +
geom_point() +
scale_y_datetime(limits =lims, breaks=date_breaks("4 hour"), labels=date_format("%H:%M"))+
theme(axis.text.x=element_text(angle=90))