0

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!

3
  • Is there a special reason why you want to solve this with a loop instead of for example ggpot2 with a long data format? Commented Mar 23, 2018 at 12:51
  • didn't think about it... and I didn't know that with ggplot2 you could do that. Im interested! Commented Mar 23, 2018 at 12:56
  • could you provide some sample data with dput(head(df))? Commented Mar 23, 2018 at 12:57

1 Answer 1

1

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()
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.