【问题标题】:ggplot2 continuous color scale AND same datetime order as in data setggplot2 连续色标和与数据集中相同的日期时间顺序
【发布时间】:2019-10-07 17:01:47
【问题描述】:

我想结合这些绘图的两个功能 - 渐变颜色和颜色条指南在图例中,如 (1) 所示,并以与 (2) 中的文件中相同的日期时间顺序绘图。

(1) 无法正确显示数据 - 我想在一个日期内连接点,而不是日期 == 5 中的 07:00:00 之后是日期 == 10 中的 07:00:00。

d = ggplot(data.test, aes(x = fakeTime, y = Wh, col = Date)) + geom_line() +
scale_colour_gradient2()

(2) 这个问题解决了here 使用日期作为因子,它不允许连续色标。

data.test <- transform(data.test,Date=factor(Date,levels=unique(Date)))
d = ggplot(data.test, aes(x = fakeTime, y = Wh, col = Date)) + geom_line() +
 scale_colour_hue(l = 20, c = 60)

fakeTime 是因为另一个堆栈交换答案而创建的,该答案通过引入一个新日期来解决同时绘制不同日期的相同时间(如 (2) 中),该日期在所有值中都是相同的。最终,从 datetime 中提取了正确的日期,并在 Date 列中找到,例如5 代表实际日期为 2019-03-05。

这是我的示例数据集,可供阅读

read.csv("data.csv", header = TRUE, sep = ",", stringsAsFactors = FALSE)
"Date","time","Wh","fakeTime"
5,"07:00:00",0.45,2019-03-01 07:00:00
5,"08:00:00",6.14,2019-03-01 08:00:00
5,"09:00:00",6.89,2019-03-01 09:00:00
5,"10:00:00",13.26,2019-03-01 10:00:00
5,"11:00:00",12.66,2019-03-01 11:00:00
5,"12:00:00",27.05,2019-03-01 12:00:00
5,"13:00:00",14.41,2019-03-01 13:00:00
5,"14:00:00",5.75,2019-03-01 14:00:00
5,"15:00:00",2.78,2019-03-01 15:00:00
5,"16:00:00",1.37,2019-03-01 16:00:00
5,"17:00:00",0,2019-03-01 17:00:00
10,"07:00:00",0.32,2019-03-01 07:00:00
10,"08:00:00",6.12,2019-03-01 08:00:00
10,"09:00:00",22.88,2019-03-01 09:00:00
10,"10:00:00",10.32,2019-03-01 10:00:00
10,"11:00:00",18.33,2019-03-01 11:00:00
10,"12:00:00",23.17,2019-03-01 12:00:00
10,"13:00:00",22.21,2019-03-01 13:00:00
10,"14:00:00",27.09,2019-03-01 14:00:00
10,"15:00:00",12.78,2019-03-01 15:00:00
10,"16:00:00",4.22,2019-03-01 16:00:00
10,"17:00:00",0.94,2019-03-01 17:00:00

【问题讨论】:

    标签: r datetime ggplot2 time-series


    【解决方案1】:

    尝试在 ggplot() 和 geom_line(aes(col = Date)) 中的 aes() 内设置 group = Date

    ggplot(data.test, aes(x = fakeTime, y = Wh, group = Date)) + geom_line(aes(col = 
    Date)) +
    scale_colour_gradient2()
    

    【讨论】:

    • 我认为我们需要使用 as.numeric(Date) 正如你最初提出的那样。
    猜你喜欢
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 2017-08-26
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多