A line graph for each row

advertisements

I am trying to make a line graph of each row of my data frame traff The x axis would be the year from 2006 to 2012.

The final result should be a separate graph for each line. In the example below the first graph represents the third line and the second one the second line (see table below):

I know how to find the max value of each row to get the max yaxis with:

xaxis <- colnames (traff[,(3:10)])

But I am struggling to make a loop for each row and generate a line graph. As you see each port (a, b and c) has three categories (IntPass, Pass and Cruise).

Port    Category    2006    2007    2008    2009    2010     2011    2012
a       IntPass     9046000 0       9579000 9683700 10404900 0       0
a       Pass        270000  260000  360000  360000  342000   385000  368000
a       Cruise      259     238     269     263     247      258     265
b       IntPass     8249304 8222336 8692362 9015726 9107665  9177075 9050424
b       Pass        0       272584  351267  437437  381141   407162  463770
b       Cruise      260     255     265     293     261      263     274
c       IntPass     6760000 6514294 7247366 7257646 7900000 8500000  8800000
c       Pass        305026  294738  377522  416605  392000  443000   442000
c       Cruise      289     268     298     305     279     293      294


You should not use a for loop for drawing lines into a chart. The ggplot package does it for your if your category variable is a factor. Have a look at the following code:

library(reshape2) #install.packages("reshape2")
library(ggplot2) #install.packages("ggplot2")

#Import data into a Data frame
data <- c("
Port    Category    2006    2007    2008    2009    2010     2011    2012
a       IntPass     9046000 0       9579000 9683700 10404900 0       0
a       Pass        270000  260000  360000  360000  342000   385000  368000
a       Cruise      259     238     269     263     247      258     265
b       IntPass     8249304 8222336 8692362 9015726 9107665  9177075 9050424
b       Pass        0       272584  351267  437437  381141   407162  463770
b       Cruise      260     255     265     293     261      263     274
c       IntPass     6760000 6514294 7247366 7257646 7900000 8500000  8800000
c       Pass        305026  294738  377522  416605  392000  443000   442000
c       Cruise      289     268     298     305     279     293      294
")
traff <- read.table(text = data, header=TRUE)

#Reshape the data for ggplot
traff2 <- melt(traff,id=c("Port","Category"),variable.name = "Year")

#Remove the X in the Year column and convert it to number
traff2$Year <- as.numeric(gsub(pattern="X",replacement = "",x = as.character(traff2$Year)))

#The data is ready for ggplot
head(traff2)

#ggplot it...
ggplot(traff2, aes(x = Year, y = value, color = Port))+
facet_grid(facets = Category~., scales = "free_y")+
  geom_line()+theme_bw()

Result: