首页 > 解决方案 > 如何使用日期数据创建线图?

问题描述

ggplot(data=A, aes(x = Date, y = WaterLevel)) +  geom_line(aes(color = Location))
dput(droplevels(head(A, 20)))
structure(list(Date = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L), .Label = c("2018-01-01", 
"2018-01-02", "2018-01-03", "2018-01-04"), class = "factor"), 
    Typhoon = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "", class = "factor"), 
    Location = structure(c(2L, 1L, 5L, 4L, 3L, 2L, 1L, 5L, 4L, 
    3L, 2L, 1L, 5L, 4L, 3L, 2L, 1L, 5L, 4L, 3L), .Label = c(" Upstream Af & Midstream Bf", 
    " Upstream Bf", "Downstream Af", "Downstream Bf", "Midstream Af"
    ), class = "factor"), WaterLevel = c(-0.02, -1.83, 0.56, 
    -3.64, 3.11, -0.01, -1.83, 0.56, -3.63, 3.11, 0.01, -1.83, 
    0.56, -3.64, 3.1, 0.01, -1.71, 0.83, -3.63, 3.1)), row.names = c(NA, 
20L), class = "data.frame")

在此处输入图像描述

数据格式错了吗?

结果目前看起来像这样

在此处输入图像描述

标签: r

解决方案


将“日期”列从类别转换factor为有效Date

library(dplyr)
library(ggplot2)
A %>%
    mutate(Date = as.Date(Date)) %>%
    ggplot(aes(x = Date, y = WaterLevel)) +
           geom_line(aes(color = Location))

推荐阅读