2012-11-13 54 views
3

我想叠加一个直方图和一个表示使用r的晶格包的累积分布函数的xyplot。重叠柱状图和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)) 

stacked plots

我想这些在同一帧叠加,而不是叠加。

下面的代码不起作用,也不做任何我已经尝试它的简单变化:

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

回答

4

你在自定义面板功能的正确轨道上。诀窍是将正确的参数传递给panel. - 函数。对于panel.histogram,这意味着通过公式并供给一个适当的值的breaks论点:

EDIT上的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") 
      }) 

enter image description here

3

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

来自graphics包的hist()函数有一个选项,称为add。以下是你想要的“古典”方式:

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

+1 - 我认为这是一个很好的答案。有时候一个简单的解决方案就是需要的。 – thelatemail