简体   繁体   中英

Adding multiple lines to plot, without ggplot

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,])}

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

结果图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM