在 ggplot 输出上使用 coord_flip() 后添加大括号

Adding underbrace after using coord_flip() on ggplot output

我正在尝试在 ggplot 输出的底部水平添加一个下括号,其 x-y 已被翻转(使用 coordin_flip())。我将使用 mtcars 示例数据进行说明。

library(ggpubr)

data("mtcars")
dfm <- mtcars
# Convert the cyl variable to a factor
dfm$cyl <- as.factor(dfm$cyl)
# Add the name colums
dfm$name <- rownames(dfm)
# Subset the data
head(dfm[, c("name", "wt", "mpg", "cyl")])

# Sort by group and by ascending order

g <- ggbarplot(dfm, x = "name", y = "mpg",
          fill = "cyl",       # change fill color by cyl
         color = "white", # Set bar border colors to white
          palette = "jco",  # jco journal color palett. 
          sort.val = "asc",  # Sort the value in dscending order 
          sort.by.groups = TRUE, # Sort inside each group
          x.text.angle = 90 # Rotate vertically x axis texts
          ) + labs(title="Brand & MPG", y = " ", x = " Brand") + coord_flip()
          

          

然后我想在 ggplot 对象的底部添加一个水平花括号,使原始图看起来像这样。

所以我引用了 this post 并调用了 ggbrace 包,通过添加以下行修改代码:

g + geom_brace(aes(x=c(0,-3), y=c(0,35), label = "something"), inherit.data=F, rotate=90, labelsize=5) + coord_cartesian(y=range(dfm$mpg), clip = "off")

# coord_cartesian() is used in order to put the underbrace outside of the plotting area (at the bottom).

但是,Rreturns一个错误信息:

Coordinate system already present. Adding new coordinate system, which will replace the existing one.

关于如何调整 geom_brace() 函数内的参数以通过最少的修改获得所需结果的任何建议?

报错好像是不能同时使用coord_flipcoord_cartesian,所以首先要把coord_cartesian参数全部输入coord_flip.

然后,由于 x 是分类的,因此必须进行一些修改,以便 geom_bracecoord_flip 以相同的方式理解输入。

最后,你必须旋转 270 度而不是 90 度。

结果是:

ggbarplot(dfm, x = "name", y = "mpg",
               fill = "cyl",       # change fill color by cyl
               color = "white", # Set bar border colors to white
               palette = "jco",  # jco journal color palett. 
               sort.val = "asc",  # Sort the value in dscending order 
               sort.by.groups = TRUE, # Sort inside each group
               x.text.angle = 90 # Rotate vertically x axis texts
) + labs(title="Brand & MPG", y = " ", x = " Brand") + 
  geom_brace(aes(x=c(-1,0), y = c(0,35), label = "something"), inherit.data=F, rotate=270, labelsize=5) +
  coord_flip(clip="off", expand = FALSE,x=range(seq_along(dfm$name))) +
  theme(plot.margin = unit(c(0., 0., 0.5, 0.), units="lines"))