使用ggplot2重塑要在R中打印的数据
我想使用ggplot2绘制3条线。 我的数据是这样的使用ggplot2重塑要在R中打印的数据,r,plot,ggplot2,reshape,R,Plot,Ggplot2,Reshape,我想使用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 x y 1 1 -4800 25195.73 2 1 -2800 1
print(x)
V1 V2 V3 V4
1 -4800 25195.73 7415.219 7264.28
2 -2800 15195.73 5415.219 7264.28
从这个例子中,我了解到我需要将我的数据重塑为如下内容:
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
如何进行此整形?使用
restrape2
library(reshape2)
x$id <- seq_len(nrow(x))
melted <- melt(x, id.vars = c('id','V1'))
# rename
names(melted) <- c('id', 'x', 'variable', 'y')
library(重塑2)
x$id基本重塑可以实现以下功能:
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
现在运行以下命令:
newx<-reshape(oldx, dir="long", idvar="V1",varying=c("V2","V3","V4"), v.names="y")
names(newx) <- c('x','id','y')
现在使用新的tidyr::pivot\u longer
库(tidyverse)
mydat%pivot_更长(cols=-V1)
#>#tibble:6 x 3
#>V1名称值
#>
#>1-4800 V2 25196。
#>2-4800 V3 7415。
#>3-4800 V4 7264。
#>4-2800 V2 15196。
#>5-2800 V3 5415。
#>6-2800 V4 7264。
#或者你也可以直接通过管道将其发送到你的ggplot调用
mydat%>%
枢轴长度(cols=-V1)%>%
ggplot(aes(V1,值,颜色=名称))+
geom_线()
由(v0.3.0)于2020年7月30日创建
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