Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

r - Plotting multiple data in a data frame at fixed column intervals with corresponding legend in one single plot

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...