2

I would like to plot multiple lines on the same plot, without using ggplot.

I have scores for different individuals across a set time period and wish to plot a line between yearly scores for each individual. Data is organised with each row representing an individual and each column an observed value in a given year.

Currently I am using a for loop, but am aware that this is often not efficient in R, and am interested if there are any more suitable approaches available within base R.

I will be working with up 100,000 individuals

Thanks.

Code:

df=data.frame(runif(10,0,100),runif(10,0,100),runif(10,0,100),runif(10,0,100))
df=data.frame(t(df))

Years=seq(1,10,1)

plot(1,type="n",xlab="Year",ylab="Score", xlim=c(1,10), ylim=c(0,100))

for(x in 1:4){lines(Years,df[x,])}
1
  • 1
    For loops aren't "inefficient" in R, they're just not necessary in many cases due to vectorization. In this case, I'd use the same code you did. If you convert the data frame to a matrix, you can use matplot, but you'll need to tweak the defaults and set type = 'l'. Commented Jan 24, 2017 at 15:29

1 Answer 1

2

Efficiency is not much of a consideration when plotting since plotting to a device is a slow operation in itself. You can use matplot (which uses a loop internally). It's basically a more sophisticated version of your code wrapped in a function.

matplot(Years, t(df), xlab="Year", ylab="Score", type = "l")

resulting plot

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.