繁体   English   中英

使用 ggplot2 重塑数据以在 R 中绘制

[英]Reshaping data to plot in R using ggplot2

我想使用 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   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))
melted <- melt(x, id.vars = c('id','V1'))
# rename
names(melted) <- c('id', 'x', 'variable', 'y')

使用新的tidyr::pivot_longer现在非常简单

library(tidyverse)

mydat <- read.table(text = "V1       V2       V3      V4
1 -4800 25195.73 7415.219 7264.28
2 -2800 15195.73 5415.219 7264.28") 
  
mydat %>% pivot_longer(cols = -V1) 
#> # A tibble: 6 x 3
#>      V1 name   value
#>   <int> <chr>  <dbl>
#> 1 -4800 V2    25196.
#> 2 -4800 V3     7415.
#> 3 -4800 V4     7264.
#> 4 -2800 V2    15196.
#> 5 -2800 V3     5415.
#> 6 -2800 V4     7264.

# or you could then pipe this directly to your ggplot call 
mydat %>% 
  pivot_longer(cols = -V1) %>%
  ggplot(aes(V1, value, color = name)) +
  geom_line()

reprex 包(v0.3.0) 创建于 2020-07-30

基本重塑可以解决问题:

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

产生:

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  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM