3

I have a data frame x3 of 30 columns generated using the following codes, I would like to plot in a single plot the first column to be x axis and y-axis should be columns 5,10,15,20,25 and 30.

x <- c(1:10)
y <- x^3
z <- y-20
s <- z/3
t <- s*6
q <- s*y
x1 <- cbind(x,y,z,s,t,q)
x2 <- cbind(x1,x1*5)
x3 <- cbind(x1,x1*5,x2*2,x1+2)
x3 <- data.frame(x3)

To plot multiple y-data (columns 5,10,15,20,25,and 30) vs the same x-axis data, I use this following piece of code,

plt <- ggplot() + 
  lapply(seq(5,ncol(x3),5),         
         function(x){              
           geom_line(aes(x=x3[1], y=x3[x]),                           
                     color=variable,                                
                     size=1.5) + scale_y_continuous()                                          
         }) +   xlab('x') +  ylab('y')

But I get error in do.call("layer" .. Could someone please point out what I need to modify in the above code to display the data in a proper manner along with the legend.

Thanks

6
  • you should reshape your data.frame to long format, see reshape2::melt. Commented Jan 23, 2014 at 13:06
  • @baptiste Once I melt the data frame x3, how can I reference only certain columns to be plotted like in this case, col 5,10,15,20,25, and 30. Commented Jan 23, 2014 at 13:14
  • i give my data pet names, it's easier to identify them. Numbers are cold-blooded. You can, if you need to, use names(x3)[c(5, 10, 15, 20)] instead and use the default names assigned by R when you created the data.frame. You might need aes_string if you take that route. Commented Jan 23, 2014 at 13:35
  • @baptise So i use this, but I get error in aesthetics length, x3_m <-melt(x3, id=names(x3)[1]) ; p <- ggplot(x3_m, aes_string(x=names(x3)[1],y= names(x3)[c(5, 10, 15, 20)]))+ geom_point(aes(color = variable), size = 1) Commented Jan 23, 2014 at 13:43
  • 1
    Your melted data, as it stands, has three columns: names(x3)[1], value, and variable. So you want ggplot(x3_m, aes(names(x3)[1], value, colour=variable)+ geom_line(). To select specific variables from the original data, either specify them in melt() as meas.vars, or use subset(x3_m, variable %in% names(x3)[c(5, 10, 15, 20)])) before plotting. Commented Jan 23, 2014 at 13:49

1 Answer 1

3

Use melt to reshape your data into long format:

x4 <- melt(x3, id=c("x"), measure=c("t","s.1","z.2","y.3","x.4","q.4"), variable = "cols")

Then create your plot with:

ggplot(x4) +
  geom_line(aes(x=x, y=value, color=cols), size=1) + 
  scale_y_continuous() 

which gives:

enter image description here

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.