【问题标题】:Making a line graph using ggplot2 using dates使用 ggplot2 使用日期制作折线图
【发布时间】:2021-09-23 22:41:49
【问题描述】:

所以我有一个日期列表和相应的数据如下:

DATE        Event
7/14/2021   Start
7/14/2021   Start
7/14/2021   Start
7/14/2021   Start
7/13/2021   Start
7/12/2021   Start
7/12/2021   Start
7/12/2021   Start
7/12/2021   Start
7/12/2021   Start
7/12/2021   Start
7/11/2021   Start
7/11/2021   Start
7/6/2021    Submit
6/30/2021   Submit
6/25/2021   Submit
6/24/2021   Submit
6/23/2021   Submit
6/22/2021   Submit
6/22/2021   Submit

我想要做的就是用两条线绘制 1 个图:

  • x 轴:日期
  • y 轴:记录数
  • 第 1 行:开始
  • 第 2 行:提交

我正在尝试用 ggplot 和 tidyverse 来做这件事,欢迎任何帮助!!

【问题讨论】:

    标签: r date ggplot2 tidyverse


    【解决方案1】:

    ** 看到您的评论,如果您想根据事件字段有单独的行,请在函数ggplot() 中使用参数group。您也可以按事件添加颜色。我已将其添加到代码中。

    这应该适合你。查找以“# 这是您感兴趣的部分”开头的内联注释。

    # original data
    df = data.frame(DATE........Event = c("7/14/2021   Start",
                                          "7/14/2021   Start","7/14/2021   Start",
                                          "7/14/2021   Start","7/13/2021   Start",
                                          "7/12/2021   Start","7/12/2021   Start","7/12/2021   Start",
                                          "7/12/2021   Start","7/12/2021   Start",
                                          "7/12/2021   Start","7/11/2021   Start","7/11/2021   Start",
                                          "7/6/2021   Submit","6/30/2021   Submit",
                                          "6/25/2021   Submit","6/24/2021   Submit",
                                          "6/23/2021   Submit","6/22/2021   Submit","6/22/2021   Submit")
    )
    
    # had to fix the data, because of the way you posted it
    names(df)[1] <- "Date"
    df <- separate(df, Date, into = c("Date", "Event"), sep = "   ")
    
    # this is the part you're interested in
    # first you need the date to be a date object
    # the library lubridate is the best option for simplicity
    df <- df %>% mutate(Date = lubridate::mdy(Date))
    
    # then you can graph the count
    #               and group by event**
    ggplot(df, aes(x = Date, 
                   group = Event,
                   color = Event)) + 
      geom_line(stat = "count")
    

    这是它的样子:

    【讨论】:

    • 这不完全是,我需要一行用于 Starts,一行用于 Submits,两行一个绘图。
    • 这看起来更正确,你能更新剧情吗?
    • @John Thomas 我在最初更新代码后更新了图表。不过,那是在您发表评论之前。该图与代码对齐。也许你在我改变它的时候正在看它?
    • 仅供参考@Kat,您可以在 Windows(和 linux,我认为)上使用 read.table("clipboard", header = TRUE) 和在 macos 上使用 read.table(pipe("pbpaste"), header=TRUE) 更轻松地读取数据(在突出显示问题中的数据文本和复制)。它将以两列框架的形式读入,而不需要 separate(.)(尽管它仍然需要 mdyas.Date)。
    猜你喜欢
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2013-10-22
    相关资源
    最近更新 更多