【问题标题】:Plotting several lines in one diagramm在一个图表中绘制多条线
【发布时间】:2018-11-03 23:35:50
【问题描述】:

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

有什么建议吗?

【问题讨论】:

  • color = Datum Datum 是什么?也许改变color = Weekday
  • 对不起,我的意思是“日期”而不是基准。如果我更改为 color = weekday,它并没有真正改变,因为我的列表中只有星期一。
  • 你能用 dput 函数给我们一个包含两个星期一的样本数据集吗?
  • 您的日期和时间戳是日期/时间还是 as.factor?

标签: r ggplot2 aesthetics


【解决方案1】:

您的问题是您需要 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

我得到以下图表

我认为这就是您所需要的,如果您需要更多关于格式化 x 轴和图例的帮助,请告诉我

干杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 2020-05-25
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    相关资源
    最近更新 更多