-1

I have the following dataframe:

  STATE STATEFP `2000` `2005` `2010` `2015`
  <chr>   <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
1 AL          1  0.958  0.953  0.953  0.944
2 AR          5  0.373  0.354  0.322  0.314
3 AZ          4  0.493  0.514  0.583  0.541
4 CA          6  0.604  0.675  0.608  0.326
5 CO          8  0.819  0.818  0.862  0.856
6 CT          9  0.870  0.817  0.748  0.791

Now I want to make a line plot where 2000, 2005, 2010 and 2015 are place on the x-axis and the values in those columns are plotted. Each line should then have a color which corresponds with the right State.

Do I have to transfer my data or is it easier?

Roelalex1996
  • 53
  • 1
  • 7
  • 1
    A small request, for future questions: the output you've provided is mostly good, but `tibble`'s output here requires some cleanup for us to use (the `\`` surrounding atypical column names, and the class row with ``, etc). While this is better than many questions, it is often easier when the question includes the output from `dput` (as in my answer), so that we have an unambiguous copy of the data. Minor, really, but any little bit can help sometimes. Thanks! – r2evans Mar 12 '21 at 15:14

2 Answers2

2

Hi you can use tidyr's pivot longer for this:

library(tidyr)
library(ggplot2)
iris %>% pivot_longer(Sepal.Length:Petal.Width) %>% 
  ggplot(aes(name,value, colour= Species))+geom_boxplot()


  • pivot_longer rearranges the first four columns to longer format creating the name (=former column name) column and a value column.

  • ggplot plots the piped output using geom_boxplot

user12256545
  • 2,755
  • 4
  • 14
  • 28
2

ggplot2 expects "long" data, not wide.

library(ggplot2)
# library(tidyr) # pivot_longer
tidyr::pivot_longer(dat, `2000`:`2015`, names_to = "year") %>%
  ggplot(., aes(year, value)) +
  geom_path(aes(color = STATE, group = STATE))

enter image description here


Data

dat <- structure(list(STATE = c("AL", "AR", "AZ", "CA", "CO", "CT"), STATEFP = c(1L, 5L, 4L, 6L, 8L, 9L), `2000` = c(0.958, 0.373, 0.493, 0.604, 0.819, 0.87), `2005` = c(0.953, 0.354, 0.514, 0.675, 0.818, 0.817), `2010` = c(0.953, 0.322, 0.583, 0.608, 0.862, 0.748), `2015` = c(0.944, 0.314, 0.541, 0.326, 0.856, 0.791)), class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))
r2evans
  • 141,215
  • 6
  • 77
  • 149
  • 1
    Thanks! I already had the longer frame but I pivoted that one wider. Your tip about ''geplot expects long data'' did the job. Thanks a million! – Roelalex1996 Mar 15 '21 at 08:19