首页 文章

排除ggplot中每个方面中未使用的因子级别

提问于
浏览
1

考虑这个数据框:

df <- data.frame(vars=c(rnorm(3),rnorm(3,2,1), rnorm(3,1,1)),
             names=c("a","b","c","a","d","b","c","a","f"),
             groups=c(rep("x",3),rep("y",3),rep("z",3)))

我正在用ggplot绘制这个:

ggplot(df, aes(reorder(names, vars), names)) +    geom_bar(stat="identity") +
theme_bw() + facet_grid(groups~., scales="free_x") + coord_flip() +     ylab(NULL) + xlab(NULL)

它看起来像这样

enter image description here

我现在想要以下内容:

  • 每个网格项应丢弃未使用的项目,例如在"x"网格中应该没有"d"和"f"

  • x轴应该是"vars"列的值 . 每个网格中的比例应该相同,应该删除整体x比例 . 我只想让每个网格中的条形比例保持不变

  • 每个网格中的条形应按递减顺序排列(顶部较长条形)

update

使用here的建议编辑我收到此错误:

ggplot(df, aes(names,vars)) + geom_bar(stat="identity") + coord_flip() + 
  theme_bw() + facet_wrap(~groups,nrow = 3,scales = "free_x")

Error in facet_render.wrap(plot$facet, panel, plot$coordinates, theme,  : 
  ggplot2 does not currently support free scales with a non-cartesian    coord or coord_flip.
In addition: Warning message:
Stacking not well defined when ymin != 0

当我删除coord_flip()它工作但我仍然得到警告,结果不是我想要的 .

1 回答

  • 1

    这是一个解决方法,但它给出了一个情节,似乎符合您的基本目标 . geom_bar 被替换为 geom_seqment ,因为它似乎更接近您正在绘制的内容,并避免了 coord_flip 的复杂性 . 条形的顺序由 group 中的 vars 的等级确定 . 无法直接指定y轴标签,但您可以使用 geom_text 将正确的 names 值放在y轴旁边,以便它们充当标签 . 此外,我将小平面标签切换到左侧,这似乎改善了小平面和y轴标签的整体外观 .

    set.seed(177)
    df <- data.frame(vars=c(rnorm(3),rnorm(3,2,1), rnorm(3,1,1)),
                     names=c("a","b","c","a","d","b","c","a","f"),
                     groups=c(rep("x",3),rep("y",3),rep("z",3)))
    
    library(ggplot2)
    sp1 <- ggplot(data=transform(df, ranked=ave(vars, groups, FUN=rank)),
                      aes( x=vars, y=ranked))
    sp1 <- sp1 + geom_segment( aes( xend = 0,  yend = ranked), size=10)
    sp1 <- sp1 + geom_text( aes( x = min(vars), y= ranked, label = names), hjust= 4)
    sp1 <- sp1 + scale_y_discrete(label=NULL)
    sp1 <- sp1 + theme_bw()
    sp1 <- sp1  + facet_grid( groups ~ .,  scales="free", switch="y")
    plot(sp1)
    

    情节看起来像

    enter image description here

相关问题