我使用ggplot2在时间序列的x轴标签上遇到了问题。
在阅读了大量的文章(例如,这篇文章:Time Axis Values Incorrect in some ggplot plots but not others)并尝试了他们的解决方案之后,我仍然没有正确地使用x轴(也在安装了最新版本的ggplot2库(“ ggplot2”之后, lib.loc =“〜/ R / win-library / 3.4”))。
到目前为止,我设法创建了该图: Daily activity pattern of individuals averaged over a month
如您所见,我在两天内绘制了相同的数据,以使夜间活动更加清晰可见。
我想以%H:%M的方式保留标签。
问题似乎在这一行:
scale_x_datetime(date_breaks ='6 hours',expand = c(0,0),标签= date_format(“%H:%M”,tz =“ UTC”))
如果我使用labels = date_format(“%H:%M”,tz =“ UTC”)参数,则会得到错误的x轴标签。使用自变量,标签从22:00到22:00,尽管应该从00:00到00:00。
我真的很想解决方案。 这里是data和情节的代码。
activitydata$year <- as.numeric(year(activitydata$ts))
activitydata$month <- as.numeric(month(activitydata$ts))
activitydata$day <- as.numeric(day(activitydata$ts))
activitydata$hour <- as.numeric(hour(activitydata$ts))
activitydata <- data.table(activitydata)[order(animal_id, hour),,]
activitydata_day <- group.CI(act_xy_ma2 ~ month + hour + animal_id, data = activitydata, ci = 0.95)
activitydata_day$animal_id <- as.factor(activitydata_day$animal_id)
activitydata_day$h <- as.POSIXct(paste(activitydata_day$hour, "00:00", sep = ":"), format = "%H:%M:%S", origin="1970-01-01")
activitydata_day <- as.data.table(activitydata_day)
activitydata_day2 <- activitydata_day
activitydata_day2$h <- activitydata_day2$h + (60*60*24)
activitydata_day3 <- activitydata_day2[hour == 0]
activitydata_day3$h <- activitydata_day3$h + (60*60*24)
activitydata_day <- rbindlist(list(activitydata_day, activitydata_day2, activitydata_day3))
titl <- paste("Daily activity pattern averaged over month", 3, sep = " ")
ggplot() +
geom_line (data = activitydata_day[animal_id == 103 & month == 3], aes(x=h, y = act_xy_ma2.mean, col= animal_id), size = 1) +
scale_x_datetime(date_breaks = '6 hours',expand = c(0,0), labels = date_format("%H:%M", tz= "UTC") ) +
ggtitle(titl) + xlab("Hour of the day") + ylab("Mean acceleration rate") +
scale_colour_brewer(palette = "Paired") +
scale_fill_brewer(palette = "Paired") +
theme_minimal()
为了使我的问题更可重复,这里是用dput()创建的R输出:
structure(list(animal_tag = c("103_2299", "103_2299", "103_2299",
"103_2299", "103_2299", "103_2299"), ts = structure(c(1172703600,
1172703900, 1172704200, 1172704500, 1172704800, 1172705100), class = c("POSIXct",
"POSIXt")), act_x = c(12L, 23L, 17L, 26L, 25L, 18L), act_y = c(16L,
33L, 26L, 41L, 51L, 19L), act_xy = c(28L, 56L, 43L, 67L, 76L,
37L), act_xy_ma2 = c(42L, 50L, 55L, 72L, 56L, 54L), animal_id = c(103L,
103L, 103L, 103L, 103L, 103L), tag_code = c("2299", "2299", "2299",
"2299", "2299", "2299"), threshold_period = c("2007-09", "2007-09",
"2007-09", "2007-09", "2007-09", "2007-09"), year = c(2007, 2007,
2007, 2007, 2007, 2007), month = c(3, 3, 3, 3, 3, 3), day = c(1,
1, 1, 1, 1, 1), hour = c(0, 0, 0, 0, 0, 0)), .Names = c("animal_tag",
"ts", "act_x", "act_y", "act_xy", "act_xy_ma2", "animal_id",
"tag_code", "threshold_period", "year", "month", "day", "hour"
), class = c("data.table", "data.frame"), row.names = c(NA, -6L
), .internal.selfref = <pointer: 0x0000000006220788>)