在以上的情况下如果也已知date 的数据框呢
时间: 2024-10-28 11:06:04 浏览: 17
如果你已经有日期(`date`)列的数据框,比如`dates`,你可以直接将其用于`plot()`函数的x轴。例如,假设你的`data`数据框包含了日期、股票名称以及对应的股票价格,你可以这样做:
```R
# 假设你的数据集样子是这样的
data <- data.frame(date = seq(as.Date("2022-01-01"), as.Date("2022-12-31"), by = "day"),
company = rep(c("AMZN", "GOOG"), each = nrow(seq.Date("2022-01-01", as.Date("2022-12-31"), by = "day"))),
price = runif(365 * 2, min = 0, max = 3000))
# 绘制折线图
plot(data$date, data$price ~ data$company, type = "l", xaxt = "n", ylab = "Stock Price",
main = "Daily Stock Prices for AMZN and GOOG", col = c("blue", "green"))
# 自动设置x轴
axis(1, at = pretty(data$date), labels = format(data$date, "%b %d"), las = 1) # 使用月份和日子
# 添加图例
legend("topright", legend = c("AMZN", "GOOG"), col = c("blue", "green"), lty = 1)
# 如果有日期列,你可以更容易地查看随时间变化的趋势
```
在这里,`xaxt = "n"`使得我们手动控制x轴的刻度,`pretty()`函数帮助我们选择合适的日期刻度,`format()`函数则将日期格式化为“月日”形式。
阅读全文
相关推荐

















