如何用 R 中的 x 轴上有日期、y 上有连续变量的图绘制一条线

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

我正在尝试绘制临床试验中观察到的招募与预计招募的情况。我在下面有一个可重现的示例,我可以在其中获得观察到的结果,但是当我尝试预测(每月 20 个)时,我无法叠加线条。

library(tibble)

# Generate 50 unique patient IDs
patient_ids <- paste0("Patient", 1:50)

# Generate random recruitment dates within a year
recruitment_dates <- sample(seq(as.Date("2024-01-01"), as.Date("2024-12-31"), by = "day"), 50)

# Create a data frame with patient IDs, recruitment dates, and recruitment order
patients <- tibble(
  Patient_ID = patient_ids,
  Recruitment_Date = recruitment_dates
)

# Sort the dataset based on recruitment dates
patients <- patients[order(patients$Recruitment_Date), ]

# Add a column for recruitment order
patients$Recruitment_Order <- 1:nrow(patients)

# Display the dataset
print(patients)

ggplot(patients, aes(x = Recruitment_Date, y = Recruitment_Order)) +
  geom_point() +
  geom_abline(slope = 20, intercept = 0, color = "red", linetype = "dashed") +
  labs(x = "Recruitment Date", y = "Recruitment Order") +
  ggtitle("Recruitment Order vs. Recruitment Date")
r ggplot2 plot time-series
1个回答
2
投票

您需要正确的单位——

Date
对象的单位是天。如果您想要一条截距为 0 在第一个日期且斜率为 20/月的线,您需要类似

sl <- 20*12/365
int <- -sl*as.numeric(min(patients$Recruitment_Date))
gg0 + geom_abline(slope = sl, intercept = int)

其中

gg0
是你的情节的其余部分。

© www.soinside.com 2019 - 2024. All rights reserved.