在一个图表中绘制几条线

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

我有一个时间序列,显示一年内每15分钟的电力负荷。我已经过滤,只显示一个特定的工作日。我的数据帧:

Date        Timestamp     Weekday    Load
2017-01-02  00:00:00      Monday     272
2017-01-02  00:15:00       Monday     400
2017-01-02  00:30:00       Monday     699
2017-01-02  00:45:00       Monday     764
2017-01-02  01:00:00       Monday     983
..
..
2017-01-09  00:45:00       Monday     764
2017-01-09  01:00:00       Monday     983
..
2017-12-25  23:45:00      Monday     983

现在我想在一个图中为每个星期一绘制几个线图:x轴=时间戳y轴=负载

我试过ggplot:

 ggplot(Loadprofile, aes(x= Timestamp, y = Load, color = Date)) + geom_line()

但这带来了以下错误

Error: Aesthetics must be either length 1 or the same as the data (4992): x, y, colour

那是输出,x轴看起来不是很连续吗?

enter image description here

有什么建议?

r ggplot2 aesthetics
1个回答
0
投票

您的问题是您需要Date作为一个因素,但是当它在Date表单上时,ggplot将其作为连续变量。

我模拟了一些数据,只是为了能够做图,下面的代码是我用来生成数据的代码:

library(tidyverse)
library(lubridate)


DateTimes <- seq(
  from=as.POSIXct("2017-1-02 0:00", tz="UTC"),
  to=as.POSIXct("2017-1-09 23:59", tz="UTC"),
  by="15 min"
)  

DF <- data.frame(Date = as.Date(DateTimes), timestamp = strftime(DateTimes, format="%H:%M:%S"), Weekday = weekdays(DateTimes)) %>% filter(Weekday == "Monday") %>% mutate(load = as.numeric(timestamp)*20 + -as.numeric(timestamp)^2 + rnorm(nrow(DF), sd = 1000) + (as.numeric(Date))) %>% mutate(load = ifelse(Date < ymd("2017_01_4"), load -5000, load))

完成后,如果我执行以下操作:

ggplot(DF, aes(x = timestamp, y = load)) + geom_line(aes(group = as.factor(Date), color = as.factor(Date

我得到以下图表

enter image description here

我想这就是你需要的,如果你需要更多帮助格式化x轴和图例让我知道

干杯

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