为什么这个facet_grid不删除列?

Wic*_*elo 3 r facet ggplot2

嗨有这个数据集:

tdat=structure(list(Condition = structure(c(1L, 3L, 2L, 1L, 3L, 2L, 
1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 
3L, 2L, 1L, 3L, 2L), .Label = c("AS", "Dup", "MCH"), class = "factor"), 
    variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 
    3L, 3L, 3L), .Label = c("Bot", "Top", "All"), class = "factor"), 
    value = c(1.782726022, 1, 2.267946449, 1.095240234, 1, 1.103630141, 
    1.392545278, 1, 0.854984833, 4.5163067, 1, 4.649271897, 0.769428018, 
    1, 0.483117123, 0.363854608, 1, 0.195799358, 0.673186975, 
    1, 1.661568993, 1.174998373, 1, 1.095026419, 1.278455823, 
    1, 0.634152231)), .Names = c("Condition", "variable", "value"
), row.names = c(NA, -27L), class = "data.frame")

> head(tdat)
  Condition variable    value
1        AS      Bot 1.782726
2       MCH      Bot 1.000000
3       Dup      Bot 2.267946
4        AS      Bot 1.095240
5       MCH      Bot 1.000000
6       Dup      Bot 1.103630
Run Code Online (Sandbox Code Playgroud)

您可以使用此代码绘制它:

ggplot(tdat, aes(x=interaction(Condition,variable,drop=TRUE,sep='-'), y=value,
                 fill=Condition)) + 
                 geom_point() +
                 scale_color_discrete(name='interaction levels')+
                                 stat_summary(fun.y='mean', geom='bar',
                 aes(label=signif(..y..,4),x=as.integer(interaction(Condition,variable))))+
                                 facet_grid(.~variable)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但正如您所看到的那样,它不会从每个方面删除未使用的列,您知道为什么吗?

Did*_*rts 5

您可以在绘图中显示所有级别,因为使用了所有级别.如果根本不使用它们,则会丢弃级别.为了消除各方面的水平添加scale="free_x"facet_grid().但是这在特定情况下不起作用,因为您xggplot()stat_summary()调用中使用不同的值语句.我建议在绘制交互之前添加新列.

tdat$int<-with(tdat,interaction(Condition,variable,drop=TRUE,sep='-'))
ggplot(tdat,aes(int,value,fill=Condition))+
  stat_summary(fun.y='mean', geom='bar')+
  geom_point()+
  facet_grid(.~variable,scales="free_x")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在这种情况下,您可以简化代码,interaction()因为您也可以使用facet_grid().

ggplot(tdat,aes(Condition,value,fill=Condition))+
  stat_summary(fun.y='mean', geom='bar')+
  geom_point()+
  facet_grid(.~variable)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述