【问题标题】:How to make line chart out of wide data in R [duplicate]如何用R中的宽数据制作折线图[重复]
【发布时间】:2018-07-30 16:03:07
【问题描述】:

我的数据表 StatePopOverTime 目前是这样的:

State 2015 2016 2017 2018 (<- Varnames) 1 Alabama 90154 87611 89638 89026 2 Alaska 42198 41308 40940 37621 3 Arizona 21110 20660 20616 20939 4 Arkansas 87421 84496 87874 89325 5 California 81735 80427 79267 80599 6 Colorado 86786 86793 85698 82927

我想使用 ggplot2 制作一个图表,其中包含 6 个折线图,说明 2015-2018 年间值的变化情况。我知道我的数据格式不正确,但我不知道是什么。我应该运行什么代码来修复我的数据表以便我可以使用 ggplot?

【问题讨论】:

    标签: r ggplot2 graph dataformat


    【解决方案1】:

    您需要先重塑数据。我建议查找诸如tidy data 之类的概念;具体来说,tidyr 包是一个很好的起点。以下应该有效:

    library(tidyverse)
    
    df <- structure(list(State = structure(1:6, .Label = c("Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado"), class = "factor"),  X2015 = c(90154L, 42198L, 21110L, 87421L, 81735L, 86786L), X2016 = c(87611L, 41308L, 20660L, 84496L, 80427L, 86793L), X2017 = c(89638L, 40940L, 20616L, 87874L, 79267L, 85698L), X2018 = c(89026L, 37621L, 20939L, 89325L, 80599L, 82927L)), class = "data.frame", row.names = c(NA, -6L))
    
    df %>%
      gather(year, value, -State) %>%
      mutate(year = str_remove(year, "X")) %>%
      ggplot(aes(x = year, y = value, color = State, group = State)) +
      geom_line()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-03
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2016-02-27
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多