Reshaping data to plot in R using ggplot2

2019-01-19 21:07发布

问题:

I want to plot 3 lines using ggplot2. My data looks like this

print(x)
     V1       V2       V3      V4
 1 -4800 25195.73 7415.219 7264.28
 2 -2800 15195.73 5415.219 7264.28

From this example, I understadn that I would need to reshape my data to something like this. Is that right?

     id       x       y      
1     1     -4800   25195.73 
2     1     -2800   15195.73
3     2     -4800   7415.219
4     2     -2800   5415.219
5     3     -4800   7264.28
6     3     -2800   7264.28

How do I do this reshaping?

Thanks!

回答1:

Use reshape2

library(reshape2)

 x$id <- seq_len(nrow(x))
melted <- melt(x, id.vars = c('id','V1'))
# rename
names(melted) <- c('id', 'x', 'variable', 'y')


回答2:

basic reshape can do the trick:

oldx = read.table(textConnection("V1 V2 V3 V4  
-4800 25195.73 7415.219 7264.28  
-2800 15195.73 5415.219 7264.28"), header=TRUE) 

print(oldx)  
     V1       V2       V3      V4  
1 -4800 25195.73 7415.219 7264.28  
2 -2800 15195.73 5415.219 7264.28 

now run this:

newx<-reshape(oldx, dir="long", idvar="V1",varying=c("V2","V3","V4"), v.names="y")  
names(newx) <- c('x','id','y') 

which yields:

print(newx)  
            x id         y  
-4800.1 -4800  1 25195.730  
-2800.1 -2800  1 15195.730  
-4800.2 -4800  2  7415.219  
-2800.2 -2800  2  5415.219  
-4800.3 -4800  3  7264.280  
-2800.3 -2800  3  7264.280