Stacking multiple plots, vertically with the same x axis but different Y axes in R

前端 未结 4 571
既然无缘
既然无缘 2020-12-24 14:39

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

相关标签:
4条回答
  • 2020-12-24 15:18

    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))
    

    enter image description here

    0 讨论(0)
  • 2020-12-24 15:21

    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")
    

    Plotting multiple y-variables against a common x-variable

    0 讨论(0)
  • 2020-12-24 15:29

    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.

    enter image description here

    0 讨论(0)
  • 2020-12-24 15:34

    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.

    0 讨论(0)
提交回复
热议问题