繁体   English   中英

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

[英]Add brackets over a bar plot of factor variable (geom_bar, geom_bracket)

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

示例数据和 plot:

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") 

阴谋

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

Error in data.frame(label = label, y.position = y.position, xmin = xmin,  : 
  arguments imply differing number of rows: 0, 1

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

为了达到您想要的结果,您可以创建一个数据框,其中包含您要绘制括号的数字xminxmax位置以及label 此外,您必须通过 y.position 传递括号中的 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)
  )

尝试这个:

ggplot(df, aes(x = reorder(country, -share), y = share)) +
  geom_bar(stat = "identity", width = 0.8, position = "dodge") +
  #add bracket
  geom_bracket(xmin = 1, xmax = 4,
               y.position = max(df$share) * 1.05,
               label = "Top 4") +
  #extend y-axis to show text on bracket
  ylim(0, max(df$share) * 1.1)

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM