【问题标题】:How to plot a list of vectors with different lengths?如何绘制不同长度的向量列表?
【发布时间】:2013-08-13 08:14:33
【问题描述】:

我有一个列表,里面有 9 个不同的向量。我想将它们(点线)绘制在一个图中,用它们的名字用不同的颜色绘制。在 R 语言中如何做到这一点?

【问题讨论】:

    标签: r list vector plot


    【解决方案1】:

    使用虚构的例子:

    # example data:
    dat <- list(a=1:5,b=2:7,c=3:10)
    # get plotting:
    plot(unlist(dat),type="n",xlim=c(1,max(sapply(dat,length))))
    mapply(lines,dat,col=seq_along(dat),lty=2)
    legend("topleft",names(dat),lty=2,col=seq_along(dat))
    

    【讨论】:

      【解决方案2】:

      没有 ggplot 答案,任何问题都是不完整的。

      dat <- list(a=1:5,b=2:7,c=3:10)
      dat <- lapply(dat, function(x) cbind(x = seq_along(x), y = x))
      
      list.names <- names(dat)
      lns <- sapply(dat, nrow)
      dat <- as.data.frame(do.call("rbind", dat))
      dat$group <- rep(list.names, lns)
      
      library(ggplot2)
      
      ggplot(dat, aes(x = x, y = y, colour = group)) +
          theme_bw() +
          geom_line(linetype = "dotted")
      

      要在单独的图中绘制每条线,请使用

      ggplot(dat, aes(x = x, y = y, colour = group)) +
          theme_bw() +
          geom_line(linetype = "dotted") +
          facet_wrap(~ group)
      

      【讨论】:

      • dat$group &lt;- rep(names(dat), lns) 将确保您的组中的名称匹配。
      • 你能把每个组都放在它自己的绘图窗口中吗?像一个侧面图。
      • @RomanLuštrik 您的数据现在是原始数据的三倍。如果你必须 ggplot,那就做对吧。将索引、分组等放在您的 ggplot 中。
      • @hplotusx 你能解释一下吗?我不确定我是否理解。
      猜你喜欢
      • 2017-07-21
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      相关资源
      最近更新 更多