向 ggplot2 ggridges (joyplot) 添加辅助轴以显示每个 bin 中的计数

Adding a secondary axis to ggplot2 ggridges (joyplot) to show counts in each bin

我用 ggridges 包制作了一个山脊图,使用 stat = 'binline' 参数为每​​个组绘制直方图。我想在左侧的辅助 y 轴上显示每组的计数,每组至少有一个或两个轴刻度。我找不到任何这样做的例子。我知道这并不简单,因为在 ggridges 中构建 y 轴的方式。有没有相对简单的方法来做到这一点?

代码:

set.seed(1)
fakedat <- data.frame(x = sample(1:10, size = 100, replace = TRUE),
                      g = letters[1:4])

library(ggplot2)
library(ggridges)

ggplot(fakedat, aes(x = x, y = g)) +
  geom_density_ridges(stat = 'binline', bins = 10, scale = 0.9) +
  theme_ridges()

剧情:

期望的输出是在每个组的基线处从零开始在左侧向上刻度,并在直方图箱中显示计数。

我认为你这样做很困难。实际上,您要做的是多面直方图。这是一个完全不使用 ggridges 的完整代表,其外观非常相似:

set.seed(1)
fakedat <- data.frame(x = sample(1:10, size = 100, replace = TRUE),
                      g = factor(letters[1:4], letters[4:1]))

library(ggplot2)

ggplot(fakedat, aes(x = x, y = ..count..)) +
  stat_bin(geom = "col",  breaks = 0:11 - 0.5, fill = "gray70") +
  stat_bin(geom = "step", breaks = 0:13 - 1) +
  facet_grid(g ~ ., switch = "y") +
  theme_classic() +
  scale_y_continuous(position = "right") +
  scale_x_continuous(breaks = 0:4 * 3) +
  theme(strip.background    = element_blank(),
        axis.text.x         = element_text(size = 16),
        axis.line.x         = element_blank(),
        axis.ticks.x        = element_line(colour = "gray90"),
        axis.ticks.length.x = unit(30, "points"),
        strip.text.y.left   = element_text(angle = 0, size = 16),
        panel.grid.major.x  = element_line(colour = "gray90"))

reprex package (v0.3.0)

于 2020-07-27 创建