带有刻面的水平条形图

时间:2016-04-05 10:49:11

标签: r ggplot2

我想生成一个包含多个水平面的图表,其中包含不同比例的条形图。但是,为了获得带有条形图的水平面,我使用coord_flip(),但这似乎与水平面不相容(可以理解)。

如何将水平条形图排列在刻面上?我知道我可以在手动grid.arrange y轴时使用cowplotelement_blank。我知道我也可以使用geom_rect,如下所示。有更直接的方式吗?

示例数据:

library(data.table) ## CJ
library(dplyr)

set.seed(1)

the_dat <- 
  data.table::CJ(
    X = LETTERS[1:5],
    Z = LETTERS[6:8]
  ) %>%
  mutate(Y = ifelse(Z == "G", 
                    # small
                    runif(n()), 
                    rnorm(n(), 100, 50))) 

使用coord_flip()会导致free_x被忽略:

library(ggplot2)

the_dat %>%
  ggplot(aes(x = X, y = Y, fill = Z)) + 
  geom_bar(stat = "identity") +
  facet_grid(~Z, scales = "free") + 
  coord_flip()

enter image description here

预期情节(大约):

enter image description here

我使用geom_rect hack:

the_dat %>%
  mutate(xf = factor(X)) %>%
  {
  ggplot(., aes(ymin = as.numeric(xf) - 0.35, ymax = as.numeric(xf) + 0.35, 
             xmin = 0, xmax = Y, fill = Z)) + 
  annotate("blank", 
           x = 0, y = unique(.$X)) +
  geom_rect() + 
  facet_grid(~Z, scales = "free")
  }

0 个答案:

没有答案