[英]Change date order at axis
我一直在為此苦苦掙扎,所以我認為現在是時候尋求幫助了...
我試圖舉一個可復制的示例,但是由於某種原因,我無法以%m-%d格式獲取我的x $ monthday :(。
x<-data.frame(seq(as.POSIXct('2012-10-01'), as.POSIXct('2015-03-01'), by= "day"))
names(x)<- "date"
x$month<- months(x$date)
x$monthday<- as.POSIXct(x$date, format= "%m-%d")
x1<- x[x$month== 'October' |x$month== 'November' | x$month== 'December' |x$month== 'January'|x$month== 'February', ]
y<- 1: nrow(x1)
x2<-cbind(x1, y)
x3<- aggregate(list(y=x2$y), list(monthday=x2$monthday), mean)
plot(x3$monthday, x3$y)
該日期的格式為%m /%d,並且具有從10月到3月的時間序列。 R從1月到12月的軸排列精美,這導致兩者之間的差距很大,因為我的數據范圍是從10月到3月。
如何在10月到3月的表格中設定x軸順序?
提前非常感謝您。
library(dplyr)
library(ggplot2)
library(lubridate)
# Fake data
dat <- data.frame(date=seq(as.POSIXct('2012-10-01'), as.POSIXct('2015-03-01'), by="day"))
set.seed(23)
dat$temperature = cumsum(rnorm(nrow(dat)))
# Subset to October - March
dat <- dat[months(dat$date) %in% month.name[c(1:2,10:12)], ]
# Calculate mean daily temperature
dat = dat %>% group_by(Month=month(date), Day=day(date)) %>%
summarise(dailyMeanTemp = mean(temperature)) %>%
mutate(newDate = as.Date(ifelse(Month %in% 10:12,
paste0("2014-", Month, "-", Day),
paste0("2015-", Month, "-", Day))))
上面的mutate
函數創建一個偽造的年份,只是為了使我們可以將日期保留為“日期”格式,並從10月到3月對其進行排序。 可能有更好的方法(也許是zoo
或xts
軟件包中的函數),但這似乎可行。
ggplot(dat, aes(newDate, dailyMeanTemp)) +
geom_line() + geom_point() +
labs(y="Mean Temperature", x="Month")
或者,在基本圖形中:
plot(dat$newDate, dat$dailyMeanTemp)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.