在一张图中绘制多条线

时间:2018-11-02 16:06:28

标签: r ggplot2 aesthetics

我有一个时间序列,显示一年中每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

有什么建议吗?

1 个答案:

答案 0 :(得分: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轴和图例的帮助,请告诉我

欢呼

相关问题