使用ggplot2重塑数据以在R中绘制 [英] Reshaping data to plot in R using ggplot2

查看:128
本文介绍了使用ggplot2重塑数据以在R中绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用ggplot2绘制3条线。
我的数据看起来像这样

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

从这个例子中,我需要重塑我的数据到这样的东西。是吗?

  id xy 
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

我该如何改变形状?

谢谢!

解决方案

使用 reshape2

  library(reshape2)

x $ id< --seq_len(nrow(x))
已融化< - melt(x,id.vars = c('id','V1' ))
#重命名
名称(熔化)< - c('id','x','variable','y')
pre>

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!

解决方案

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')

这篇关于使用ggplot2重塑数据以在R中绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆