如何在R中存在公式时绘制一个子组

时间:2015-04-27 00:17:56

标签: r boxplot

this postthis post都不适用于我的案例。

假设:

set.seed(42)
x<-rep(c("A","B","C"), c(3,4,1))
y<-rep(c("V","W"),c(5,3))
z<-rnorm(8,-2,1)
df<-data.frame(x,y,z)
boxplot(z~x+y,df)

我希望我的情节包含超过一个元素的群组。这意味着我希望我的情节只显示A.V,B.V和B.W. 此外,由于我的图表有大约70个组,我不想通过手工编写列表来实现。

由于

2 个答案:

答案 0 :(得分:5)

您可以使用paste创建新列('xy'),使用ave为包含多个元素的'xy'组创建逻辑索引,然后执行{{1} }。

boxplot

enter image description here

或使用df1$xy <- factor(paste(df1$x, df1$y, sep='.')) index <- with(df1, ave(1:nrow(df1), xy, FUN=length))>1 boxplot(z~xy, droplevels(df1[index,]))

ggplot

答案 1 :(得分:3)

您可以查看是否有任何bp$n为0和

的子集
set.seed(42)
df <- data.frame(x = rep(c("A","B","C"), c(3,4,1)),
                 y = rep(c("V","W"),c(5,3)),
                 z = rnorm(8,-2,1))
bp <- boxplot(z ~ x + y, df, plot = FALSE)
wh <- which(bp$n == 0)

bp[] <- lapply(bp, function(x) if (length(x)) {
  ## `bp` contains a list of boxplot statistics, some vectors and
  ## some matrices which need to be indexed accordingly
  if (!is.null(nrow(x))) x[, -wh] else x[-wh] 
  ## some of `bp` will not be present depending on how you called
  ## `boxplot`, so if that is the case, you need to leave them alone
  ## to keep the original structure so `bxp` can deal with it
  } else x)

## call `bxp` on the subset of `bp`
bxp(bp)

enter image description here

或者您可以使用您喜欢的任何值:

wh <- which(bp$n <= 1)

bp[] <- lapply(bp, function(x) if (length(x)) {
  if (!is.null(nrow(x))) x[, -wh] else x[-wh] 
} else x)

bxp(bp)

enter image description here