为什么这个facet_grid不删除列?

3

你好,这里有一个数据集:

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

您可以使用以下代码绘制它:
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)

enter image description here

但是,正如您所看到的,它并没有从每个分面中删除未使用的列,您知道为什么吗?

(请注意保留html标记)

1个回答

5
因为所有级别都被使用,所以图表上显示了所有级别。如果某些级别没有被使用,则会被删除。要在每个区域中删除级别,请在facet_grid()中添加scale="free_x"。但在特定情况下,这种方法不起作用,因为您在ggplot()stat_summary()调用中使用了不同的x值语句。我建议在绘图之前添加交互式新列。
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")

enter image description here

在这种情况下,你可以通过使用facet_grid()简化代码,而不必使用interaction()

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

enter image description here


哦,好的,那么这是一个 bug 吗?假设我想使用 interaction() 而不是 facet_grid(),你知道如何解决重叠问题吗? - Wicelo
更新了我的答案,展示了你代码中真正的问题并且删除了一些层级。 - Didzis Elferts
@Wicelo 这不是一个 bug。 - joran
为交互添加一个新列是个好主意,我会记住的,谢谢! - Wicelo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接