在因子变量的条形图上添加括号(geom_bar、geom_bracket)

use*_*194 2 r bar-chart ggplot2 geom-bar ggpubr

我正在尝试使用 geom_bracket 来注释有序分类条形图。

示例数据和绘图:

df <- tibble(
  country= c("ENG","ESP", "ITA", "FRA", "NLD", "POR", "AUT", "TUR", "CHE", "RUS"),
  share=c(25.71, 21.74, 11.54, 10.49,  3.76,  3.73,  2.67,  2.34,  2.07,  1.97)
) 

df %>% 
  ggplot() +
  geom_bar(aes(x = reorder(country, -share), y = share), stat = "identity", width = 0.8, position = "dodge") 
Run Code Online (Sandbox Code Playgroud)

阴谋

我尝试使用geom_bracket将条形图分组在一起(例如,前四个(ENG 到 FRA)作为“Top 4”),但无法使其工作,经常遇到以下错误消息:

Error in data.frame(label = label, y.position = y.position, xmin = xmin,  : 
  arguments imply differing number of rows: 0, 1
Run Code Online (Sandbox Code Playgroud)

如何添加一个浮动在条形上方的水平括号(y=30)?

ste*_*fan 5

为了达到您想要的结果,您可以创建一个数据框,其中包含数字xmin以及xmax要在其中绘制括号和 的位置label。此外,您还必须通过以下方式传递括号的 y 位置y.position

library(ggplot2)
library(ggpubr)

ggplot(df) +
  geom_col(aes(x = reorder(country, -share), y = share), width = 0.8, position = "dodge") +
  geom_bracket(
    aes(xmin = xmin, xmax = xmax, label = label),
    data = data.frame(xmin = c(1, 7), xmax = c(4, 10), label = c("Top 4", "Bottom 4")), y.position = c(30, 5)
  )
Run Code Online (Sandbox Code Playgroud)