【问题标题】:Add to ggplot with element of different length添加到具有不同长度元素的ggplot
【发布时间】:2013-04-06 20:47:11
【问题描述】:

我是 ggplot2 的新手,我正试图弄清楚如何在我创建的现有绘图中添加一条线。原始图是来自数据框x 的一列数据T1 的累积分布,其中包含大约100,000 个元素。我已经使用 ggplot2 和 stat_ecdf() 以及我在下面发布的代码成功地绘制了这个。现在我想使用一组 (x,y) 坐标添加另一条线,但是当我使用 geom_line() 尝试此操作时,我收到错误消息:

Error in data.frame(x = c(0, 7.85398574631245e-07, 3.14159923334398e-06,  : 
arguments imply differing number of rows: 1001, 100000

这是我尝试使用的代码:

> set.seed(42)
> x <- data.frame(T1=rchisq(100000,1))
> ps <- seq(0,1,.001)
> ts <- .5*qchisq(ps,1) #50:50 mixture of chi-square (df=1) and 0
> p <- ggplot(x,aes(T1)) + stat_ecdf() + geom_line(aes(ts,ps))

这就是从上面产生错误的原因。现在这是使用我曾经使用但我现在正试图远离的基本图形的代码:

plot(ecdf(x$T1),xlab="T1",ylab="Cum. Prob.",xlim=c(0,4),ylim=c(0,1),main="Empirical vs. Theoretical Distribution of T1")
lines(ts,ps)

我看过其他一些关于一般添加线的帖子,但我没有看到的是当两个原始向量长度不同时如何添加线。 (注意:我不想只使用 100,000 (x,y) 坐标。)

作为奖励,有没有一种简单的方法,类似于使用 abline,在 ggplot2 图形上添加一条下降线?

任何建议将不胜感激。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    ggplot 处理data.frames,您需要将ts 和ps 设为data.frame,然后在调用geom_line 时指定这个额外的data.frame:

     set.seed(42)
     x <- data.frame(T1=rchisq(100000,1))
     ps <- seq(0,1,.001)
     ts <- .5*qchisq(ps,1) #50:50 mixture of chi-square (df=1) and 0
     tpdf <- data.frame(ts=ts,ps=ps)
     p <- ggplot(x,aes(T1)) + stat_ecdf() + geom_line(data=tpdf, aes(ts,ps))
    

    【讨论】:

      猜你喜欢
      • 2017-10-14
      • 2017-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多