代码之家  ›  专栏  ›  技术社区  ›  Dr. Fabian Habersack

如何减少一根钢筋在土工格栅中的宽度?

  •  0
  • Dr. Fabian Habersack  · 技术社区  · 6 年前

    我想用ggplot得到一个并排的条形图 geom_bar() . 以下是我为复制目的编写的一些示例数据:

    dat <- data.frame("x"=c(rep(c(1,2,3,4,5),5)),
                      "by"=c(NA,0,0,0,0,NA,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1))
    

    我要绘制“X”,按“by”分组。现在,因为我不需要策划 NA 值,我筛选 !is.na(by) )

    library(dplyr)
    dat <- filter(dat, !is.na(by))
    

    现在来看情节:

    library(ggplot2)
    ggplot(dat, aes(x=x, fill=as.factor(by))) + geom_bar(position="dodge") + theme_tufte()
    

    这将返回我需要的;几乎。不幸的是,第一个条看起来真的很奇怪,因为它的binwidth是原来的两倍(因为在“by”中“x”=1没有零)。

    有没有办法把第一根横杆的宽度缩小到“正常”的程度? enter image description here

    2 回复  |  直到 6 年前
        1
  •  1
  •   Roman LuÅ¡trik    6 年前

    你也可以这样做。预先计算桌子并使用 geom_col .

    ggplot(as.data.frame(table(dat)), aes(x = x, y = Freq, fill = by)) +
      theme_bw() +
      geom_col(position = "dodge")
    

    enter image description here

        2
  •  0
  •   Dr. Fabian Habersack    6 年前

    没关系,我只是觉得你可以操纵 binwidth 参数使用 ifelse 语句。

    ...geom_bar(..., binwidth = ifelse("by"==1 & is.na("x"), .5, 1)))
    

    所以如果你玩这个,它会起作用的。至少对我有用。