在ggplot2中实现嵌套分组的多行Y轴标签(替代图例)
实现嵌套分组的多行Y轴标签(带颜色匹配)
需求说明
想把group和term两个变量做成Y轴的两行标签(分组在上,变量名在下),同时让分组标签的颜色和对应点的颜色一致,替代原有的图例。
现有代码生成的图表:
想要的目标效果:
现有代码:
data <- tibble::tribble( ~ term, ~estimate, ~conf.low, ~conf.high, ~group, "HH cultivated plots", 0.0163, -0.0130, 0.0456, "Extensive Margin", "# of farm assets (hoe, spade, axe), all HHs", 0.356, 0.143, 0.569, "Assets", "Number of plots", -0.0539, -0.158, 0.0498, "Intensive Margin", "Farm size", 0.208, -0.0394, 0.456, "Intensive Margin", "# of HH members that cultivated plots, all HHs", 0.0541, -0.0647, 0.173, "Intensive Margin", "Avg # of days HH members spent cultivating plots, all HHs", -0.192, -0.738, 0.354, "Intensive Margin", "Annual agricultural revenue", 0.329, 0.170, 0.487, "Revenue") ag_coef_plot <- data %>% ggplot( aes(x = estimate, y = term, color = group )) + geom_pointrange( # Confidence interval aes( xmin = conf.low, xmax = conf.high ), show.legend = FALSE, ) + scale_x_continuous(name = "") + geom_vline(xintercept = 0) + scale_y_discrete(name = "", limits = rev, expand = c(.05, 0)) + theme_minimal() + theme( plot.title = element_text(size = 15, hjust = 0.5, face = "bold"), plot.title.position = "plot", plot.background = element_rect(color = "black"), # 用于确保背景色不为黑色 axis.text.y = element_text(size = 15), axis.text.x = element_text(size = 15), legend.position = "left", legend.title = element_blank(), legend.text = element_blank() ) + scale_color_brewer(palette = "Set2") ag_coef_plot
解决办法
要实现目标效果,试试下面的代码:
library(tidyverse) library(ggtext) # 先给数据排序,保证同组的变量在Y轴上连续排列 data_sorted <- data %>% arrange(group, desc(term)) %>% mutate(term = factor(term, levels = term)) # 提取Set2调色板的颜色,和分组一一对应 group_colors <- scales::brewer_pal(palette = "Set2")(length(unique(data_sorted$group))) names(group_colors) <- unique(data_sorted$group) # 生成带颜色的Y轴标签:分组名(带对应颜色)换行+变量名 data_sorted <- data_sorted %>% mutate(y_label = glue::glue("<span style='color:{group_colors[group]}'>{group}</span><br>{term}")) # 绘制图表 ag_coef_plot <- data_sorted %>% ggplot(aes(x = estimate, y = y_label, color = group)) + geom_pointrange(aes(xmin = conf.low, xmax = conf.high), show.legend = FALSE) + scale_x_continuous(name = "") + geom_vline(xintercept = 0) + scale_y_discrete(name = "", limits = rev, expand = c(.05, 0)) + scale_color_brewer(palette = "Set2") + theme_minimal() + theme( plot.title = element_text(size = 15, hjust = 0.5, face = "bold"), plot.title.position = "plot", plot.background = element_rect(color = "black"), axis.text.y = element_markdown(size = 15, hjust = 1), # 用element_markdown渲染带样式的文本 axis.text.x = element_text(size = 15), legend.position = "none" # 彻底去掉图例 ) ag_coef_plot
关键点说明
- 数据排序:确保同一分组的变量在Y轴上挨在一起,排版更整齐;
- 颜色绑定:提前提取
Set2调色板的颜色,让分组标签和对应点的颜色完全匹配; - 富文本标签:用
glue生成带HTML颜色样式的标签,再通过ggtext的element_markdown渲染,实现多行带颜色的Y轴标签; - 对齐调整:
hjust = 1让Y轴文本右对齐,保证两行标签排版整齐。
内容的提问来源于stack exchange,提问作者Paula
相关产品推荐
相关产品推荐

