如何在ggplot中实现图例多组划分并自定义布局样式?
在ggplot中实现自定义分组图例样式
你可以通过调整ggnewscale配合ggplot2的图例引导(guide)和主题(theme)参数,实现目标中的分组图例样式。以下是修改后的代码:
library(ggplot2) library(ggnewscale) # 预处理数据 diamonds$cut = factor(diamonds$cut, levels=c("Fair","Good", "Very Good", "Premium","Ideal")) labels <- levels(diamonds$cut) labels <- setNames(labels, labels) labels["Fair"] <- "Very Good" labels["Good"] <- "Premium" colors <- hcl(seq(15, 325, length.out = 5), 100, 65) colors <- setNames(colors, levels(diamonds$cut)) ggplot() + # 第一个分组的图层 geom_bar(data = diamonds, aes(color, fill = cut)) + scale_fill_manual( aesthetics = "fill", values = colors, labels = labels[1:2], breaks = names(colors)[1:2], name = "First Group:", guide = guide_legend( title.position = "left", title.hjust = 0, nrow = 1, # 让该分组的图例项横向排列 order = 1 ) ) + new_scale_fill() + # 第二个分组的图层 geom_bar(data = diamonds, aes(color, fill = cut)) + scale_fill_manual( aesthetics = "fill", values = colors, labels = labels[3:5], breaks = names(colors)[3:5], name = "Second Group:", guide = guide_legend( title.position = "left", title.hjust = 0, nrow = 1, # 让该分组的图例项横向排列 order = 0 ) ) + # 调整主题样式 theme( legend.position = "bottom", legend.direction = "horizontal", legend.box = "horizontal", # 让两个图例分组并排显示 legend.box.just = "left", # 分组整体左对齐 legend.key = element_rect(fill = "white"), legend.title.align = 0 # 图例标题左对齐 )
关键调整说明:
- 在
guide_legend中设置nrow = 1,让每个分组内的图例项横向排列; - 配置
theme的legend.box = "horizontal",使两个独立图例分组并排展示; - 通过
title.hjust = 0和legend.title.align = 0确保图例标题左对齐; - 调整
order参数控制两个分组的左右显示顺序。
内容的提问来源于stack exchange,提问作者Daniel Lobo
相关产品推荐
相关产品推荐

