关于ggplot2:如何从R中的宽数据制作折线图

How to make line chart out of wide data in R

本问题已经有最佳答案,请猛点这里访问。

我的数据表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?


您需要首先重塑数据。我建议您查找诸如tidy data之类的概念;特别地,tidyr包是一个很好的起点。以下应该工作:

1
2
3
4
5
6
7
8
9
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()

Plot