I have a data.frame with multiple time series vectors against a date:time vector. I would like to plot all of the relevant vectors, vertically stacked on separate graphs wit
If you want to be old-fashioned you can use lattice
. Unlike @aaronwolen I assumed there was a missing time
variable in the data set, so I made one up:
dt$time <- seq(nrow(dt))
library(reshape2)
mm <- melt(subset(dt,select=c(time,DEPTH,X,Y,Z)),id.var="time")
library(lattice)
xyplot(value~time|variable,data=mm,type="l",
scales=list(y=list(relation="free")),
layout=c(1,4))
I agree with @PaulHiemstra, ggplot2 is the way to go.
Assuming Smooth.Vert.Speed
is the common x-axis variable against which you want to plot DEPTH
, X
, Y
and Z
...
library(ggplot2)
library(reshape2)
# Add time variable as per @BenBolker's suggestion
dt$time <- seq(nrow(dt))
# Use melt to reshape data so values and variables are in separate columns
dt.df <- melt(dt, measure.vars = c("DEPTH", "X", "Y", "Z"))
ggplot(dt.df, aes(x = time, y = value)) +
geom_line(aes(color = variable)) +
facet_grid(variable ~ ., scales = "free_y") +
# Suppress the legend since color isn't actually providing any information
opts(legend.position = "none")
Just to be different, let me mention a solution involving neither lattice nor ggplot2 -- I posted this to Romain's R Graph Gallery a few years back as entry 65 with the code here. It just stacks the graphs up, using par()
settings to keep them stacked.
Note that the vertical sizes are different by choice, they could easily be of the same height as well.
I've actually figured out another interesting way of doing this with the zoo library:
library(zoo)
z <- with(dt, zoo(cbind(DEPTH, X, Y, Z),as.POSIXct(time)))
plot.zoo(z, ylab=c("Depth (m)", "Pitch Angle (degrees)", "Swaying Acceleration (m/s^2)", "Heaving Acceleration (m/s^2)"), col=c("black", "blue", "darkred", "darkgreen"),
xlab = c("Time"), lwd=2, ylim=list((rev(range(dt$DEPTH))), c(-90,90), c(-10,10), c(-10,10)))
So within a zoo plot you can create new axis labels as a list form and all plots can have different colours.