我正在从调查数据中制作大量的图表,这些数据需要在生成的条形图旁边显示每个问题的整个文本.安排一个格罗布网格似乎是做到这一点的最佳方法.然而,我已经try 了几个包,并有同样的问题与网格排列步骤不承认输入列表的grob作为grob在grid.draw()步骤.

手动输入每个Grob的列表引用很好,但这不是一个可接受的解决方案,因为大量的绘图需要一个自动化的过程.

# Dummy data set
question <- c("Q1. A very long text like this one is hard to use as a label.",
              "Q2. A very long text like this one is hard to use as a label.",
              "Q3. A very long text like this one is hard to use as a label.",
              "Q4. A very long text like this one is hard to use as a label.",
              "Q5. A very long text like this one is hard to use as a label.")

variable <- c("V1","V2")
set.seed(42)
response <- round(runif(n = length(question) * length(variable), min = 1, max = 10), 0)

# Create a data frame
df_example <- expand.grid(Question = question, Variable = variable)
df_example$Response <- rep(response, length.out = nrow(df_example))

grob_list <- list()
for (question in unique(df_example$Question)) {
  
  # Text grob
  # used textbox_grob() over alternatives for ease of wrapping text.
  text_grob <- textbox_grob(question, x = 0.05, y = 0.5, hjust = 0, vjust = 0.5, gp = gpar(col = "black"),
                            maxwidth = 1,
                            padding = unit(c(0, 20, 0, 0), "pt"))  
  # Bar chart
  bar_chart <- ggplot(df_example, aes(x = Variable, y = Response, fill = Variable)) +
    geom_bar(stat = "identity", position = "dodge") +
    coord_flip() +
    theme_minimal() +
    theme(legend.position = "none") +
    theme(axis.title.x = element_blank()) +
    theme(axis.title.y = element_blank())

  # Convert ggplot to grob
  bar_grob <- ggplotGrob(bar_chart)
  
  # Add text and bar chart grobs to the list of grobs
  grob_list[[length(grob_list) + 1]] <- list(text_grob, bar_grob)
}

### a. Required step for automation-
# Arrange grobs from list into a grid
combined_grobs <- arrangeGrob(grob = grob_list, ncol = 2)
# returns an error at grid.draw(): 
# > Error in gList(...) : only 'grobs' allowed in "gList"


### b. Manual step that works but not practical at scale-
# Arrange grobs manually using arrangeGrob from grid
combined_grobs <- arrangeGrob(grob_list[[1]][[1]], grob_list[[1]][[2]], 
                              grob_list[[2]][[1]], grob_list[[2]][[2]],
                              grob_list[[3]][[1]], grob_list[[3]][[2]],
                              grob_list[[4]][[1]], grob_list[[4]][[2]],
                              grob_list[[5]][[1]], grob_list[[5]][[2]],
                              ncol = 2
                              )

# Display after step a or b above. 
grid.newpage()
grid.draw(combined_grobs)

推荐答案

一种更简单的方法是使用刻面和ggtext::element_textbox(_simple)自动换行问题文本:

library(ggplot2)
library(ggtext)

ggplot(df_example, aes(y = Variable, x = Response, fill = Variable)) +
  geom_bar(stat = "identity", position = "dodge") +
  facet_wrap(~Question, ncol = 1, strip.position = "left") +
  theme_minimal() +
  theme(
    legend.position = "none",
    axis.title.x = element_blank(),
    axis.title.y = element_blank(),
    strip.text.y.left = ggtext::element_textbox_simple(
      hjust = 0,
      padding = unit(c(0, 20, 0, 0), "pt")
    ),
    strip.placement = "outside"
  )

enter image description here

UPDATE要使您的代码工作,需要两个小补丁.首先,你的grob_list是一个嵌套列表,也就是说,它是格罗布listlist,而不是格罗布的list.要解决这个问题,请使用c()for循环中构建您的grob_list.其次,参数的名称是grobs=而不是grob=.

library(ggplot2)
library(gridtext)
library(grid)
library(gridExtra)

grob_list <- list()
for (question in unique(df_example$Question)) {
  text_grob <- textbox_grob(question,
    x = 0.05, y = 0.5, hjust = 0, vjust = 0.5, gp = gpar(col = "black"),
    maxwidth = 1,
    padding = unit(c(0, 20, 0, 0), "pt")
  )
  bar_chart <- ggplot(df_example, aes(x = Variable, y = Response, fill = Variable)) +
    geom_bar(stat = "identity", position = "dodge") +
    coord_flip() +
    theme_minimal() +
    theme(legend.position = "none") +
    theme(axis.title.x = element_blank()) +
    theme(axis.title.y = element_blank())
  bar_grob <- ggplotGrob(bar_chart)
  grob_list <- c(grob_list, list(text_grob, bar_grob))
}

combined_grobs <- arrangeGrob(grobs = grob_list, ncol = 2)

grid.newpage()
grid.draw(combined_grobs)

enter image description here

R相关问答推荐

列出用m n个值替换来绘制n个数字的所有方法(i.o.w.:R中大小为n的集合的所有划分为m个不同子集)

为什么当我try 在收件箱中使用合并功能时会出现回收错误?

在位置周围设定一个半径并识别该半径内的其他位置

R Tidymodels textercipes-使用spacyR进行标记化-如何从生成的标记列表中删除标点符号

根据模式将一列拆分为多列,并在R中进行拆分

修改用R编写的用户定义函数

如何删除最后一个可操作对象

DEN扩展包中的RECT树形图出现异常行为

如何指定我的函数应该查找哪个引用表?

如何将使用rhandsontable呈现的表值格式化为百分比,同时保留并显示完整的小数精度?

根据另一列中的值和条件查找新列的值

根据纬度和距离连接两个数据集

正则表达式在第二个管道和第二个T之后拆分R中的列

手动指定从相同数据创建的叠加图的 colored颜色

按组内中位数分类

在ggplot2上从多个数据框创建复杂的自定义图形

每行不同列上的行求和

Broom.Mixed::Augment不适用于Sample::分析

从字符串01JAN2021创建日期

只有当我在循环的末尾放置一条print语句时,Foreach才会给出预期的输出