【问题标题】:How to plot each list element with same x axis?如何绘制具有相同 x 轴的每个列表元素?
【发布时间】:2020-12-03 23:55:36
【问题描述】:

可重现的例子:

a <- 2
b <- 1
tau <- 2

t <- seq(1,3,1)
y <- seq(0,10,1)

G.fun <- function(x,shape,scale){pgamma(x,shape,scale)}

G <- vector(mode = "list", length = length(t))
for (t in 1:length(t)){
  G[[t]] <- G.fun(y,shape = a*t, scale = b)
}

如果 x 轴对于所有 y

【问题讨论】:

    标签: r list ggplot2 plot


    【解决方案1】:

    基础 R

    plot(y, G[[1]], pch = 16, type = "b")
    for (i in seq_along(G)[-1]) points(y, G[[i]], type = "b", pch = 16, col = i)
    

    ggplot

    (我将使用tidyr 来重塑它。)

    dat <- cbind(y=y, setNames(as.data.frame(G), c("A","B","C")))
    dat2 <- tidyr::pivot_longer(dat, -y)
    head(dat2)
    # # A tibble: 6 x 3
    #       y name     value
    #   <dbl> <chr>    <dbl>
    # 1     0 A     0       
    # 2     0 B     0       
    # 3     0 C     0       
    # 4     1 A     0.264   
    # 5     1 B     0.0190  
    # 6     1 C     0.000594
    ggplot(dat2, aes(y, value, color = name)) + geom_path()
    

    【讨论】:

      【解决方案2】:

      在基础 R 中,您还可以使用 matplot 函数。首先,您必须确保您的列表中有一个矩阵:

      mat <- do.call(cbind, G) #or even unname(as.matrix(data.frame(G)))
      matplot(y, mat, type = "b")
      

      这可以写成matplot(y, do.call(cbind, G), type = "b")

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多