Reputation: 137
I am trying to plot multiple time series in R and cannot find a quicker way than making a plot with the first column of data and manually adding the next 30 columns to it:
plot(x = SouthFOX[,1], y = SouthFOX[,2],type="l", xlab = "Year", ylab = "", ylim=c(0,max+10))
lines(x = SouthFOX[,1], y = SouthFOX[,3])
lines(x = SouthFOX[,1], y = SouthFOX[,4])
lines(x = SouthFOX[,1], y = SouthFOX[,5])
lines(x = SouthFOX[,1], y = SouthFOX[,6])
lines(x = SouthFOX[,1], y = SouthFOX[,7])
lines(x = SouthFOX[,1], y = SouthFOX[,8])
lines(x = SouthFOX[,1], y = SouthFOX[,9])
lines(x = SouthFOX[,1], y = SouthFOX[,10])
lines(x = SouthFOX[,1], y = SouthFOX[,11])
lines(x = SouthFOX[,1], y = SouthFOX[,12])
lines(x = SouthFOX[,1], y = SouthFOX[,13])
lines(x = SouthFOX[,1], y = SouthFOX[,14])
lines(x = SouthFOX[,1], y = SouthFOX[,15])
lines(x = SouthFOX[,1], y = SouthFOX[,16])
lines(x = SouthFOX[,1], y = SouthFOX[,17])
lines(x = SouthFOX[,1], y = SouthFOX[,18])
lines(x = SouthFOX[,1], y = SouthFOX[,19])
lines(x = SouthFOX[,1], y = SouthFOX[,20])
lines(x = SouthFOX[,1], y = SouthFOX[,21])
lines(x = SouthFOX[,1], y = SouthFOX[,22])
lines(x = SouthFOX[,1], y = SouthFOX[,23])
lines(x = SouthFOX[,1], y = SouthFOX[,24])
lines(x = SouthFOX[,1], y = SouthFOX[,25])
lines(x = SouthFOX[,1], y = SouthFOX[,26])
lines(x = SouthFOX[,1], y = SouthFOX[,27])
lines(x = SouthFOX[,1], y = SouthFOX[,28])
lines(x = SouthFOX[,1], y = SouthFOX[,29])
lines(x = SouthFOX[,1], y = SouthFOX[,30])
My data is a data.frame of 30 columns, with the first column as the Year, and the next 29 as measurements for each year for a given specimen:
> head(SouthFOX)
Year X050229 X050247
1 2005 NA NA
2 2004 21.34867 16.46167
3 2003 23.89700 19.67367
4 2002 19.17867 16.91817
5 2001 31.69717 21.58650
6 2000 29.51600 20.72450
My desired graph looks like this
Ideally I would like to use ggplot2, but that does not seem to be working. Thanks in advance
Upvotes: 0
Views: 1460
Reputation: 269396
Try autoplot.zoo from the zoo package. (To see each series in a separate panel omit facets=NULL
.)
DF <- data.frame(year = 1:25, a = 1:25, b = 25:1) # test data
library(zoo)
library(ggplot2)
z <- read.zoo(DF, FUN = identity)
autoplot(z, facets = NULL)
Upvotes: 0
Reputation: 13280
For base-r you can use matplot
:
mat <- matrix(runif(1000), ncol = 10)
df <- data.frame(year = 1:100, mat)
matplot(df$year, df[ ,-1], type = 'l')
For ggplot you need to restructure your data to the long format (e.g. using reshape2::melt()
:
require(ggplot2)
require(reshape2)
dfm <- melt(df, id.vars = 'year')
ggplot(dfm, aes(x = year, y = value, color = variable)) +
geom_line()
Upvotes: 1