如何在ggplot2中根据轴标签值设置线条颜色并添加图例?
解决方案
你的代码仅修改了轴标签颜色,但未关联图形线条颜色,也没利用ggplot的映射机制生成图例。以下是正确实现方式:
步骤1:预处理数据,添加分组标识
从benchmark的表达式中提取分组(csv/polars/other),用于后续颜色映射:
library(microbenchmark) library(dplyr) library(ggplot2) bmk <- microbenchmark( "A with csv" = iris %>% count(Species), "B with polars" = nrow(iris), "C with csv" = sort(names(iris)), "D with polars" = iris %>% filter(Species=="setosa"), times = 5 ) %>% mutate( group = case_when( endsWith(as.character(expr), "with csv") ~ "csv", endsWith(as.character(expr), "with polars") ~ "polars", TRUE ~ "other" ) )
步骤2:基于分组映射颜色并生成图例
利用ggplot的颜色映射机制,让线条颜色与分组绑定,同时自动生成图例,轴标签颜色也对应分组设置:
方式1:修改autoplot生成的对象
p <- autoplot(bmk) # 为图层添加颜色映射到group变量 p$layers[[1]]$aes$colour <- quote(group) p + labs(title = "polars vs others", color = "Group") + scale_color_manual( values = c("csv" = "red", "polars" = "blue", "other" = "black") ) + theme( plot.title = element_text(hjust = 0.5), axis.text.y = element_text( color = bmk %>% distinct(expr, group) %>% mutate(color = case_when(group == "csv" ~ "red", group == "polars" ~ "blue", TRUE ~ "black")) %>% pull(color) ) )
方式2:手动构建ggplot(更灵活)
ggplot(bmk, aes(x = time, y = expr, color = group)) + geom_violin(width = 0.8) + geom_point(size = 2, alpha = 0.6) + labs(title = "polars vs others", x = "Execution Time", y = "Expression", color = "Group") + scale_color_manual( values = c("csv" = "red", "polars" = "blue", "other" = "black") ) + theme( plot.title = element_text(hjust = 0.5), axis.text.y = element_text( color = bmk %>% distinct(expr, group) %>% mutate(color = case_when(group == "csv" ~ "red", group == "polars" ~ "blue", TRUE ~ "black")) %>% pull(color) ) )
关键说明
- 通过将
color映射到group变量,ggplot会自动生成对应图例 scale_color_manual指定分组对应的颜色规则- 轴文本颜色通过提取每个表达式的分组颜色设置,保证与线条颜色一致
内容的提问来源于stack exchange,提问作者Damien Dotta
相关产品推荐
相关产品推荐

