使数据框的每一行成为不同的折线图,并在R中的相同图上绘图

时间:2018-01-15 18:40:49

标签: r ggplot2

我有以下代码:

x1 <- list(1,2,3,4,5)
x2 <- list(1,4,7,8)
x3 <- list(5,6)
x4 <- list(9,0,0,5,6,7)
myList <- list(x1, x2, x3, x4)

df <- data.frame(t(sapply(myList, function(x){
c(x, rep(tail(x, 1), max(lengths(myList)) - length(x)))})))

创建一个这样的数据框:

  X1 X2 X3 X4 X5 X6
1  1  2  3  4  5  5
2  1  4  7  8  8  8
3  5  6  6  6  6  6
4  9  0  0  5  6  7

如何为数据框的每一行创建单独的折线图,并将它们全部绘制在同一图上,其中X1,X2,X3,X4,X5,X6显示y值随时间的变化。 / p>

1 个答案:

答案 0 :(得分:0)

只需复制akrun's comment以尝试关闭问题。

matplot(t(df), type = 'l', xaxt = 'n')
 legend('topright', colnames(df), col = seq_along(df), fill = seq_along(df))
 axis(1, at = seq_along(df), labels = colnames(df))

enter image description here