ggplot2 条形图,条内有线条

ggplot2 bar chart with lines inside bars

我正在制作一个绘图,其中我有一个从 facet_wrap 获得的 3x3 网格。九个地块中的八个使用 geom_violin,而其余地块使用 geom_bar。在网站上找到一些有用的答案后,我就可以正常工作了。我遇到的问题是,当我对条形图使用 fill = "white, color = "black" 时,它会在条形图 内部 绘制这些线。

这是一些示例代码和数字。

library(tidyverse)
n <- 100
tib <- tibble(value = c(rnorm(n, mean = 100, sd = 10), rbinom(n, size = 1, prob = (1:4)/4)),
              variable = rep(c("IQ", "Sex"), each = n),
              year = factor(rep(2012:2015, n/2)))
ggplot(tib, aes(x = year, y = value)) + 
  facet_wrap(~variable, scales = "free_y") +
  geom_violin(data = filter(tib, variable == "IQ")) +
  geom_bar(data = filter(tib, variable == "Sex"), stat = "identity", 
           color = "black", fill = "white")

现在回答我的问题:如何去除条形内的这些线条?我只希望它是白色的,带有黑色边框。我一直在尝试各种配置,我可以设法摆脱线条,但代价是把小平面搞砸了。我相当确定它与统计数据有关,但我在尝试修复它时不知所措。有什么建议吗?

我建议在条形图中总结数据:

ggplot(tib, aes(x = year, y = value)) + 
  facet_wrap(~variable, scales = "free_y") +
  geom_violin(data = filter(tib, variable == "IQ")) +
  geom_bar(data = tib %>%
             group_by(year,variable) %>%
             summarise(value=sum(value)) %>%
             filter(variable == "Sex"),
           stat = "identity", 
           color = "black",
           fill = "white")

我不确定这是表示数据的好方法,不同面板的 y 轴代表非常不同的事物,但请接受您的示例可能与您的实际用例不匹配。单独绘制然后使用 gridExtra::grid.arrangecowplot::plot_grid 可能是更好的解决方案。

但是如果你想这样做

ggplot(tib, aes(x = year, y = value)) + 
  facet_wrap(~variable, scales = "free_y") +
  geom_violin(data = filter(tib, variable == "IQ")) +
  geom_col(data = filter(tib, variable == "Sex") %>%
                  group_by(year, variable) %>% 
                  summarise(value = sum(value)), 
    fill = "white", colour = "black")

使用 geom_col 而不是 geom_bar 所以我不需要使用 stat = identity.