【问题标题】:superpose a histogram and an xyplot叠加直方图和 xyplot
【发布时间】:2012-11-02 09:10:09
【问题描述】:

我想用 r 的 lattice 包叠加一个直方图和一个表示累积分布函数的 xyplot。

我尝试使用自定义面板功能来完成此操作,但似乎无法做到这一点——我认为一个情节是单变量的,而另一个情节是双变量的。

这是我要垂直堆叠的两个图的示例:

set.seed(1)
x <- rnorm(100, 0, 1)

discrete.cdf <- function(x, decreasing=FALSE){
    x <- x[order(x,decreasing=FALSE)]
    result <- data.frame(rank=1:length(x),x=x)
    result$cdf <- result$rank/nrow(result)
    return(result)
}

my.df <- discrete.cdf(x)

chart.hist <- histogram(~x, data=my.df, xlab="")
chart.cdf <- xyplot(100*cdf~x, data=my.df, type="s",
                    ylab="Cumulative Percent of Total")

graphics.off()
trellis.device(width = 6, height = 8)
print(chart.hist, split = c(1,1,1,2), more = TRUE)
print(chart.cdf, split = c(1,2,1,2))

我希望这些叠加在同一个框架中,而不是堆叠。

以下代码不起作用,我尝试过的任何简单变体也不起作用:

xyplot(cdf~x,data=cdf,
          panel=function(...){
              panel.xyplot(...)
              panel.histogram(~x)
          })

【问题讨论】:

    标签: r histogram lattice


    【解决方案1】:

    这个答案只是一个占位符,直到有更好的答案出现。

    graphics 包中的hist() 函数有一个名为add 的选项。以下以“经典”方式执行您想要的操作:

    plot( my.df$x, my.df$cdf * 100, type= "l" )
    hist( my.df$x, add= T )
    

    【讨论】:

    • +1 - 我认为这是一个很好的答案。有时,一个简单的解决方案正是我们所需要的。
    【解决方案2】:

    您的自定义面板功能走在了正确的轨道上。诀窍是将正确的参数传递给panel.- 函数。对于panel.histogram,这意味着传递公式并为breaks 参数提供适当的值:

    编辑 y 轴上的正确百分比值和图的type

    xyplot(100*cdf~x,data=my.df,
              panel=function(...){
                  panel.histogram(..., breaks = do.breaks(range(x), nint = 8),
                    type = "percent")
                  panel.xyplot(..., type = "s")
              })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 2021-12-20
      • 2020-07-30
      • 1970-01-01
      • 2020-08-08
      • 2019-09-25
      • 1970-01-01
      相关资源
      最近更新 更多