在 R 中的 facet_wrap ggplot 中的括号上方添加多个 titles/text

Add multiple titles/text above brackets in facet_wrap ggplot in R

我想在括号上方添加“Pear”和“Apple”作为文本。我找不到将其添加为多个标题、相同大小和相同位置的方法。

df <- data.frame('fruit'=c("Apple", "Apple", "Apple", "Apple", "Pear", "Pear"),
                'color'=c("Red", "Red", "Green","Green","Green","Green"), fruitcol=c(rep("AppleRed",2), rep("AppleGreen",2),rep("PearGreen",2)), 'percentage'= c(11,19,34,23,27, 16))

df$fruitcol <- factor(df$fruitcol,  levels = c("AppleRed", "AppleGreen", "PearGreen"),labels = c( "Red", "Green", "Green_"))


the_plot<- ggplot(data=df, aes(x=fruit, y=percentage)) +
geom_bar(stat="identity") + facet_wrap(~fruitcol, labeller = label_parsed) + labs(title = "Pear", subtitle="Apple")+ theme(plot.subtitle=element_text(size=18, hjust=0.5, face="italic", color="black"))+
scale_x_discrete("",breaks=c(.5,2.5),labels=c("Low types","High types") ) +
theme(axis.ticks = element_blank(), axis.ticks.length = unit(.85, "cm"), strip.background = element_rect(
     color="black", fill="#FC4E07", size=1.5, linetype="solid"))

library(pBrackets)
the_plot
grid.locator(unit="native") 
top_y <- 40
grid.brackets(55, top_y,   360, top_y, lwd=2, col="black")
grid.brackets(370, top_y,  518, top_y, lwd=2, col="black")

我喜欢 teunbrand 的嵌套面选项,但这里有一个技巧:

通常情况下,您可以在绘图面板外进行注释。

您需要手动为标签选择合理的主题边距和 y 值。

我也很高兴得知我很长一段时间都被误认为 df 是一个基本函数。我终于可以放弃说服人们停止将其用于数据框的努力。感谢 teunbrand

library(tidyverse)
library(ggtext)
library(grid)
library(pBrackets)

df <- data.frame('fruit'=c("Apple", "Apple", "Apple", "Apple", "Pear", "Pear"),
                 'color'=c("Red", "Red", "Green","Green","Green","Green"), fruitcol=c(rep("AppleRed",2), rep("AppleGreen",2),rep("PearGreen",2)), 'percentage'= c(11,19,34,23,27, 16))

df$fruitcol <- factor(df$fruitcol,  levels = c("AppleRed", "AppleGreen", "PearGreen"), labels = c( "Red", "Green", "Green_"))

df$title_lab <- rep(c("Pear", "italic('Apple')",""), each = 2)

mypercent <- 
  df %>%
  group_by(fruit, color) %>%
  summarise(sum_perc = sum(percentage))
maxperc <- max(mypercent$sum_perc)
the_plot<-
  ggplot(data = df, aes(x=fruit, y=percentage)) +
  geom_col() +
  geom_text(aes(x = 1, y = maxperc + 15, label = title_lab), parse = TRUE)+
  facet_wrap(~ fruitcol, labeller = label_parsed) +
  scale_x_discrete(NULL, breaks=c(.5,2.5), labels=c("Low types","High types") ) +
  coord_cartesian(clip = "off", ylim = c(NA, maxperc)) +
  theme(axis.ticks = element_blank(), 
        strip.background = element_rect(
    color="black", fill="#FC4E07", size=1.5, linetype="solid"),
    plot.margin = margin(t = .5, unit = "in")) 


the_plot
grid.locator(unit="native") 
top_y <- 40
grid.brackets(55, top_y,   360, top_y, lwd=2, col="black")
grid.brackets(370, top_y,  518, top_y, lwd=2, col="black")

grid.text(x=unit((55+360)/2, 'native'), y=unit(top_y-28, 'native'), label="XXXX", hjust = 0.5, vjust=0)

将在您的括号上方添加 XXXX。
但是在我的测试中,支架的宽度与你的不同,所以它们没有正确对齐。

这不是一个特别巧妙的解决方案 - 因为图形宽度的变化会把它搞砸。为了可重复性,我想要 55 和 360,可能 top_y 都以编程方式定义,而不是鼠标点击