rdata: drawing lines on a plot per subset of data

712 views Asked by At

I feel like I should be able to accomplish this one with call to lines() but I have the following:

data <- read.csv(...)
set1 <- subset(data, level='one')
set2 <- subset(data, level='two')
set3 <- subset(data, level='three')
plot(x=data$year, y=data$output)
lines(x=set1$year, y=set1$output, col='red')
lines(x=set2$year, y=set2$output, col='blue')
lines(x=set3$year, y=set3$output, col='green')

This feels like a really 101 application plot and lines and I'd just like to make it more efficient, especially given I'll end up having N number of subset calls.

1

There are 1 answers

0
qzr On

You could just use a loop of the sort

colors <- c('red', 'blue', 'green')
levels <- c('one', 'two', 'three')

# make sure you made a new plot up to this point and that its limits are set correctly

for (i in 1:length(colors)) {
    d <- subset(data, level=levels[i])
    lines(x=d$year, y=d$output, col=colors[i])
)

This scales nicely to large N. You can also produce lists of colors with e.g. colors <- rainbow(N).

If you want to do it without a loop, you could look at matplot and matlines which plot columns of matrices against eachother. But for this all your subsets would have to be of equal length, which I suppose isn't true in your case.