Search code examples
rplotrescale

Multiple line plots with different scales


I'd like to plot time-dependent trend of physical features of music.

For example,

from 1980 to 2010, the average song duration (unit: 100000 ms)
from 1980 to 2010, the average loudness (unit: 20dB)

You could see they come with different scales, it'll be straightforward to draw line plot over time for each of these features.

But if I have say, 30 such features, so is it appropriate to include all these line plots into the same graph? (Because it'll be kind of waste to draw 30 independent line plot.)

If so, how can I overcome the problem of different scaling(100000ms vs 20dB)? I should re-scale data first?

thx


Solution

  • Here's a ggplot approach (illustrated with fake data):

    library(reshape2)
    library(ggplot2)
    library(ggthemes)
    
    # Fake data
    dat = mtcars[order(mtcars$mpg), c(1,3:7,11)]
    dat = cbind(dat, setNames(dat, LETTERS[1:7]), setNames(dat, LETTERS[8:14]), 
                setNames(dat, LETTERS[15:21]), setNames(dat[,1:2], LETTERS[22:23]), 
                year=1980:(1980 + nrow(dat) - 1))
    
    # Melt data to long format and plot
    ggplot(melt(dat, id.var="year"), aes(year, value)) +
      geom_line(lwd=0.3) +
      facet_wrap(~ variable, ncol=5, scales="free_y") +
      theme_tufte(base_size=7) +
      expand_limits(y=0)
    

    enter image description here