Search code examples
rplotline-plot

R: in a line plot, how do you control the character used for each point (rather than for each series)?


I'm making a line plot with several lines/series. I'd like to have different characters for each point within a line/series.

The code I currently have is something like:

x <- rep(1:5, 4) * rep(rnorm(5), each = 4)
x <- matrix(x, 5, 4)
matplot(x, type = "b", pch = 1:4)

However, 'pch' only allows you change the character used for all points in one series. Is there any way to control each point individually?

Many thanks!


Solution

  • plot allows a different pch per point within a series; matplot doesn't (it only allows a different one for each series). So you will have to use plot/points/lines instead of matplot.

    e.g.

    xs <- 1:nrow(x)
    cols <- c('blue', 'red', 'black', 'green', 'yellow')
    
    # set up empty plot with the right limits
    matplot(x, type='n')
    for (i in 1:ncol(x))
      lines(xs, x[, i], type='b', pch=(i - 1)*(1:nrow(x))+1, col=cols[i])