R语言gglikert按Theme分面绘图空行问题的解决求助
解决gglikert分面绘制时的空行问题
问题原因
你当前先将全量数据转为宽格式(所有问题作为列)再分面的方式,会导致每个分面显示所有问题——而不同主题的问题不重叠,没有对应数据的问题就会呈现为空行。
解决方法
按Theme分组,为每个主题单独生成gglikert图,再用patchwork包拼接所有子图,确保每个子图只显示对应主题的问题,彻底消除空行。
步骤1:安装并加载依赖包
如果未安装patchwork,先执行安装:
install.packages("patchwork") library(patchwork) library(purrr) # 用于批量处理分组数据
步骤2:定义绘图函数
创建一个复用函数,输入单个主题的数据集,输出对应的Likert图:
# 自定义Likert颜色(可根据需求调整) custom_colors <- c( "Very \n Dissatisfied" = "#d73027", "Dissatisfied" = "#fc8d59", "Neutral" = "#ffffbf", "Satisfied" = "#91bfdb", "Very \n Satisfied" = "#4575b4" ) plot_likert_by_theme <- function(sub_df) { # 将单主题数据转为宽格式 wide_sub <- sub_df %>% mutate(row = row_number()) %>% pivot_wider(names_from = Question, values_from = response) %>% select(-row) # 生成gglikert图 gglikert(wide_sub, add_totals = TRUE, totals_color = "black", data_fun = data_fun) + # 保留你自定义的data_fun逻辑 labs(y = NULL, title = unique(sub_df$Theme)) + theme( text = element_text(size = 10), plot.title = element_text(color = "black", face = "bold", hjust = 0.5), axis.text.y = element_text(size = 9) ) + scale_y_discrete( position = "left", labels = function(x) str_wrap(sub(".*?\\.", "", x), width = 50) ) + scale_fill_manual(values = custom_colors, guide = guide_legend(nrow = 1)) }
步骤3:批量绘图并拼接
按主题拆分数据,批量生成子图后垂直拼接:
# 按Theme拆分数据集 theme_dfs <- split(df, df$Theme) # 为每个主题生成对应图表 theme_plots <- map(theme_dfs, plot_likert_by_theme) # 拼接所有图表,统一图例位置 combined_plot <- wrap_plots(theme_plots, ncol = 1) + plot_layout(guides = "collect") & theme(legend.position = "bottom") # 查看最终效果 combined_plot
效果说明
每个子图仅包含对应主题的问题,无空行;所有图表样式保持一致,图例统一显示在底部,可读性更强。
内容的提问来源于stack exchange,提问作者Homer Jay Simpson
相关产品推荐
相关产品推荐

