使用基本的 Rplot() 函数绘制每周数据,但希望标签均匀分布且不重复月年?

问题描述 投票:0回答:1

我正在尝试创建一个简单的散点图,所以 x 轴上是周,y 轴上是“案例”,每个案例都用点表示,并注意我只能使用基本 R 的plot(),不能使用 ggplot。

我有 156 周(约 3 年)的数据,这些周固定为 2020 年 3 月 19 日日期(前后 7 天以创建每周间隔)。因此,许多周都在同一个月开始,或者在其间隔内包括两个不同月份的边界。

我试图仅获取 x 轴标签上的 36 个月-年,但似乎无法将 156 个数据点(我使用周开始日进行跟踪)与 x 轴解耦标签,所以我要么得到重复的月年,要么得到不均匀间隔的刻度线。有没有办法使用基本的 R 的plot() 函数来做到这一点?我无法使用 ggplot。我想也许我需要的是 ggplot 的scale_x_date() 的某种基本plot() 版本?

我尝试使用 as.Date 将文本日期转换为实际日期格式,然后直接绘制它,但这仍然会导致 x 轴标签上重复月份...

这是一个玩具示例,尝试绘制周 x 案例的图表,但希望标签为月年而不是周:

Lines <- "Week_Interval        Cases     Week_Start
19-01-03-19-01-09   696537   2019-01-03
19-01-03-19-01-09   718748   2019-01-10
19-01-17-19-01-23   799355   2019-01-17
19-01-24-19-01-30   805800  2019-01-24
19-01-31-19-02-06   701262  2019-01-31
19-02-07-19-02-13   531579  2019-02-07
19-02-14-19-02-20   690068  2019-02-14
19-02-21-19-02-27   756947  2019-02-21
19-02-28-19-03-06   718757  2019-02-28
 9-03-07-19-03-13  701768    2019-03-07
19-03-14-19-03-20  820113   2019-03-14
19-03-21-19-03-27  645259   2019-03-21"


exampledata <- read.table(textConnection(Lines), header = TRUE)


exampledata$Date <- as.Date(exampledata$Week_Start)
# Plot outcome variable versus time
plot(exampledata$Date,exampledata$Cases,
main="Weeks by Cases",
ylab="Cases",
ylim=c(500000,900000),
xlab="",
las=2,
col="red",
xaxt="n")

# Add x-axis year labels
axis(1, exampledata$Date, format(exampledata$Date, "%b, %Y"))

# Add in the points for the figure
points(exampledata$Date,exampledata$Cases,
col="red",
pch=20)
r plot time-series
1个回答
0
投票

您可以将非

duplicated
1 日到 7 日
substr
的日期进行子集化。

> plot(exampledata$Date, exampledata$Cases, main="Weeks by Cases", ylab="Cases",
+      ylim=c(500000, 900000), xlab="", las=2, col="red", xaxt="n", pch=20)
> ats <- exampledata$Date[!duplicated(substr(exampledata$Date, 1, 7))]
> axis(1, at=ats, labels=strftime(ats, '%b %Y'))
© www.soinside.com 2019 - 2024. All rights reserved.