0

enter image description here


enter image description here

A glimpse of data set and a expected plot outcome.

Ramprasath Selvam
  • 3,868
  • 3
  • 25
  • 41
koliii
  • 109
  • 1
  • 8
  • 2
    Please do not post data as a picture. Make your example reproducible and show what you've tried so far and where you are stuck. See also [How to make a great R reproducible example](https://stackoverflow.com/a/5963610/5892059) – kath Aug 08 '19 at 06:54

2 Answers2

1

Here's an example data:

dat <- data.frame(state=rep(c("a", "b", "c"), each=18), 
                  year=rep(2001:2018, 3), 
                  cases=sample(0:180, 18*3), 
                  injured=sample(0:180, 18*3), 
                  killed=sample(0:180, 18*3))

Convert the example data into a long-format:

library(tidyverse)
dat0 <- dat %>% gather(var, val, -year, -state)

Visualise with ggplot2:

ggplot(dat0, aes(year, val, colour=var)) + geom_line() + facet_wrap(~state, ncol=1)

enter image description here

Adam Quek
  • 6,973
  • 1
  • 17
  • 23
  • Thanks @Adam, what is "var" and "val" in function gather(var, val, -year, -state)? – koliii Aug 08 '19 at 09:12
  • It's just two dummy names I'd created for the long format (var = variable, val = value). This way, I will know that for each row, what is the value referring to (is it cases, injured or killed). You can name it to anything you wish of course. You could also keep it, and change the labels with ggplot commands. – Adam Quek Aug 08 '19 at 09:16
0

If I have understood you correctly, this is what you're after.

#First melt table into long form
table <- reshape2::melt(table, id.vars=c("State","Year","Cause"))

#Next create a plot-function (value and variable are standard names given by melt, change them beforehand if you want them to be called something else.)
make.plot <- function(table){
   gplt <- ggplot(data=table, 
               mapping = aes(x=Year, y=value, color=variable)) + 
          geom_line()
}

#Now do this for each subset
#(there are apply functions that would work here, but I'm not all too proficient using them, so have a loop.)

plots <- list()
states <- unique(table$State)

for(s.idx in seq_along(states)){
   subtable <- subset(table, State==states[s.idx]
   plt <- make.plot(subtable)
   plots[[s.idx]] <- plt
}

#To add the different linetypes, just specify linetype=variable in aes()

Jarn Schöber
  • 309
  • 1
  • 8