使用ggplot2重新整形数据以在R中绘图

Ign*_*cio 5 plot r 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
Run Code Online (Sandbox Code Playgroud)

从这个例子中,我强调我需要将我的数据重塑为这样的东西.是对的吗?

     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
Run Code Online (Sandbox Code Playgroud)

我该如何重塑?

谢谢!

mne*_*nel 6

使用 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')
Run Code Online (Sandbox Code Playgroud)


Tje*_*ebo 4

现在对于新的来说非常简单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()
Run Code Online (Sandbox Code Playgroud)

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