在beanplot {beanplot}中使用'wd ='来动态更改bean的宽度

时间:2013-06-28 18:10:40

标签: r plot boxplot kernel-density density-plot

我正在使用beanplot包的beanplot函数,我无法找到一种方法来使用wd=参数并获得良好的结果。

我想要什么

  • 显示beanpots,其宽度取决于样本的大小。
  • (现在)了解'wd ='的用法以及如何使用它。

到目前为止,当我尝试使用wd参数时,作为一个列表,它给了我一个错误,作为一个向量,它给了我一些奇怪的东西(wd似乎乘以密度估计值)

示例

library(beanplot)
set.seed(2000)
Test <- data.frame(
  x=rnorm(30), 
  f1 = factor(c(rep('A', 10), rep('B',20))), 
  f2=factor(c('M','F'))
  )

beanplot(x~f1,Test,
         col=list('orange','yellow'),
         wd=c(1:2/2),
         boxwex = 1
)

beanplot1 http://i41.tinypic.com/wcmg4j.jpg

1 个答案:

答案 0 :(得分:3)

好的,经过一些个人试验/错误后,我得到了两个答案:

首先,在查看代码之后,不应该以这种方式使用wd,并且不支持具有多个值(与'col ='不同)。似乎'wd ='并不意味着直接用于指定正常使用中的beanplot宽度。实际上,当没有提供'wd'(或wd = NA)时,wd从'maxwidth ='计算,但归一化到所有密度函数的最高值。因此,如果想要控制bean的宽度,则指定'maxwidth ='似乎更合适。

其次,我写了一些代码来实际实现我想要的东西。它可能是凌乱的,请随意增强它。此示例可用于本机函数beanplot不支持的任何参数变体。

您会注意到代码显示了为什么'wd ='仍然很重要的示例,因为我们希望对所有密度图都对bean的所有宽度值进行一次归一化。

col_list = list('orange','yellow')
wd_fac = aggregate(x~f1,Test,length)$x # get the size relative to the number of points in each bean
wd_fac <- wd_fac/max(wd_fac)

par(mfrow=c(1,2))
## Normal plot
beanplot(x~f1,Test, col=col_list)
## Our plot
bp <- beanplot(x~f1,Test,what=c(T,F,F,F)) # plots the line and frames + get the general parmeters
sapply(1:length(levels(Test$f1)),
       function(X){
         beanplot(subset(Test, f1 == levels(f1)[X])$x,
                  col=col_list[X],
                  bw = bp$bw, # we may want to keep the bandwidth
                  wd= bp$wd*wd_fac[X], 
                  at=X,
                  what=!c(T,F,F,F),
                  add = T)}
)

beanplot http://i39.tinypic.com/33uxrhf.png