具有刻面比例和动态 geom_text 位置的 ggplot

ggplot with facet scale and dynamic geom_text position

我正在使用 gglot 和 facet_wrap 来绘制一些数据。不同方面的维度非常不同(0.2 与 2000)。

我绘制 geom_bar 并在条上方添加具有相同值的 geom_text。现在有一个问题。 geom_text 值适用于标题下方的 "big" 个栏。

我看到了两个可能的解决方案,但我都无法实施。

  1. 切换 geom_text 大条形图的位置。这可以用 aes 中的 vjust 来完成。但是对于每个方面,切换点必须不同。

  2. 我想将 y-axis 缩放到 110%,所以文本有 space。但我不想手动把它放到我的程序中,因为情节是自动完成的。

我使用的代码

library(ggplot2)
testdata <- data.frame(a = c(0.1,0.2,0.3, 4,5,6, 7000,8000,9000),
                   b = c('a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c' ),
                   c = c('aa', 'bb', 'cc', 'aa', 'bb', 'cc', 'aa', 'bb', 'cc'))

ggplot(testdata, aes(x = c, y = a)) +
  geom_bar(stat = 'identity') +
  geom_text(aes(label = a), vjust = -1) +  
  facet_wrap(~b, ncol=1, scales = 'free_y')

这是适合您的解决方案:

*(如果您想了解更多详情,请查看此 Whosebug question and answer

library(data.table)
testdata <- data.table(testdata)
testdata[,y_min:= a*0.5, by = c]
testdata[,y_max:= a*1.5, by = c]

ggplot(testdata, aes(x = c, y = a)) +
  geom_bar(stat = 'identity') +
  geom_text(aes(label = a), vjust = -1) + 
  facet_wrap(~b, ncol=1, scales = 'free_y') +
  geom_blank(aes(y = y_min)) +
  geom_blank(aes(y = y_max))

您首先需要为每个组创建 y_miny_max 变量。 "plot" 他们通过 geom_blank()