Cisco
Cisco

Reputation: 137

Loop inside a plot for multiple points()

I have a data.frame (df) with 17 rows and 40 columns. I would like to plot all those columns like this:

windows()
plot(NULL,xlim=c(0,17),ylim=c(5000,90000),xaxt='n',xlab="", ylab="")
points(df$c1,type="b",pch=15,col="gold3")
points(df$c2,type="b",pch=15,col="gold3")
.  
.
points(df$c40,type="b",pch=15,col="gold3")

I would like to create a loop inside the plot to not have to write all the lines for the 40 columns. I tried different things without success. Thanks in advance!

Upvotes: 0

Views: 259

Answers (1)

drmariod
drmariod

Reputation: 11802

Here is an example using standard plot and points as well as a ggplot2 example.

df <- data.frame(x=1:10,
       y1=rnorm(10),
       y2=rnorm(10),
       y3=rnorm(10))
plot(df$x, df$y1)
# points(df$x, df$y2)
# points(df$x, df$y3)
for(i in 3:4) {
  points(df$x, df[[i]])
}


library(reshape2)
library(ggplot2)
melt_df <- melt(df, 'x')
ggplot(melt_df, aes(x, value)) +
  geom_point()

Upvotes: 1

Related Questions