【问题标题】:plotting weekdays (mon, tue, etc) of Dates of a dataframe in x-axis in R在 R 中的 x 轴上绘制数据框日期的工作日(星期一、星期二等)
【发布时间】:2018-02-27 03:08:17
【问题描述】:

这是在 R ver3.4.2 编程中。我将根据日期的工作日绘制数据框的某个变量,比如 Y。我已经通过一些参考资料,但到目前为止没有一个工作。我尝试了以下方法:(数据框有日期、时间和 Y)

library(dplyr)
library(lubridate)
library(datasets)
df$Date<- as.Date(df$Date, "%d/%m/%Y")
df$Time<- strptime(df$Time, "%H:%M:%S")
df$Time<- as.POSIXct(df$Time)
#select data for certain dates
selected_data<-with(df, df[(Date >= "2017-01-12" & Date <= "2017-01-13"),])
Y<- as.numeric(as.character(selected_data$Y))
#these are my trials in trying to plot the weekdays
#trial 1
wkdays <- weekdays(selected_data$Date)
#trial 2
dat <- format(selected_data$Date,"%Y-%m-%d")

pl<-plot(dat,Y, type="l" , ylab = "Y", xlab=" ")
#pl<-plot(wkdays, Y, type="l" ,xaxt="n", ylab = "Y", xlab=" ")
#pl<- plot(Y, type="l", ylab = "Y", xlab=" ")
axis(1,at=as.Date.numeric(selected_data$Date), labels=format(weekday))
#axis.Date(1, at=seq(weekday), "days",labels = TRUE)
#axis.Date(1, at=seq(min(wkdays),max(wkdays), by = "%d"), "days",labels = TRUE,tcl = -0.2)
axis(2, at= seq(0, max(Y), by = 2))

输出应该是 Y 数据与索引的折线图,刻度标记有日期(周一、周二等)的工作日,具有一定的刻度间隔。

如果有人有答案的链接(也许我有不同的关键字),请帮助并在下面分享。谢谢!

这是一个示例数据集:

Date;Time;Y;
2017-01-12;2018-02-27 00:00:00;"0.715";
2017-01-12;2018-02-27 00:01:00;"0.438";
2017-01-12;2018-02-27 00:02:00;"0.734";
2017-01-12;2018-02-27 00:03:00;"0.646";
2017-01-12;2018-02-27 13:19:00;"1.268";
2017-01-13;2018-02-27 13:20:00;"0.108";
2017-01-13;2018-02-27 13:21:00;"0.961";
2017-01-13;2018-02-27 13:22:00;"0.570";
2017-01-13;2018-02-27 13:23:00;"0.192";
2017-01-13;2018-02-27 13:24:00;"1.280";

【问题讨论】:

标签: r plot data-analysis


【解决方案1】:

这是使用ggplot2 包中的scale_x_date(date_breaks = "day", date_labels = "%a") 的解决方案。查看更多herehere

由于您没有提供数据,我生成了一个随机数据以供使用。

library(ggplot2)

set.seed(2017)
date <- seq(from = as.Date("2017-12-01"), to = as.Date("2017-12-13"),
            by = "days")
value <- runif(length(date), 1, 1000)
dat <- data.frame(date, value)

ggplot(dat, aes(x = date, y = value)) + 
  geom_point() + 
  geom_line() +
  scale_x_date(date_breaks = "day", date_labels = "%a") +
  theme_bw()

要包括日期和月份:

ggplot(dat, aes(x = date, y = value)) + 
  geom_point() + 
  geom_line() +
  scale_x_date(date_breaks = "day", date_labels = "%a\n%b %d") +
  theme_bw()

reprex package (v0.2.0) 于 2018 年 2 月 26 日创建。

【讨论】:

  • 感谢您的帮助。日期仅为“2017-01-12”和“2017-01-13”,我在帖子中添加了一个示例数据集。我已经尝试过你的代码,但我使用了我的日期,但它返回了一个错误 -->“错误:美学必须是长度 1 或与数据相同 (2880): x, y”..
猜你喜欢
  • 1970-01-01
  • 2015-08-02
  • 1970-01-01
  • 2019-04-08
  • 2014-02-11
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
  • 2020-02-24
相关资源
最近更新 更多