如何调整ggplot2图例中线条的粗细?
解决ggplot2图例线条加粗无效的问题
问题分析
你遇到的核心问题是:通过guide_legend(override.aes = list(size = 15))设置图例线条加粗时,要么无效果,要么图例整体放大但线条区分度仍不足。这是因为设置的size数值过大,导致图例的key区域被过度撑开,视觉上掩盖了线条加粗的效果;同时geom_line的aes中同时绑定了color和size因子映射,需要精准覆盖参数。另外你的代码存在语法错误:temp %>应改为temp %>%,否则无法正常运行。
修正后的代码
library(ggplot2) library(dplyr) library(countrycode) set.seed(123) temp <- data.frame( Year = rep(1995:2020, times = 12), Country = rep(c("ABW", "AFG", "AGO", "AIA", "ALB", "AND", "ANT", "ARE", "ARG", "ARM", "AUT", "ETH"), each = 26), deg_in_norm = runif(12 * 26, min = 0, max = 1), deg_out_norm = runif(12 * 26, min = 0, max = 1) ) highlighted_countries <- c("ZAF", "SAU", "RUS", "IRN", "IND", "ETH", "EGY", "CHN", "BRA", "ARG", "ARE") temp <- temp %>% mutate(Color = ifelse(Country %in% highlighted_countries, as.character(Country), "Not BRICS")) %>% mutate(Size = ifelse(Country %in% highlighted_countries, 1, 0)) %>% mutate(Full_names = ifelse(Country %in% highlighted_countries, countrycode(Country, origin = 'iso3c', destination = 'country.name'), "Not BRICS")) %>% group_by(Country) %>% mutate(id = cur_group_id()) %>% ungroup() ggplot(data = temp) + geom_line(aes(x = Year, y = deg_in_norm, color = factor(Color), size = factor(Size), group = id)) + scale_color_manual(values = c("ARE" = "black", "ARG" = "#6699CC", "ETH" = "#44AA99", "Not BRICS" = "grey"), labels = c("United Arab Emirates", "Argentina", "Ethiopia", "Not BRICS")) + scale_size_manual(values = c("0" = 0.5, "1" = 1.5), guide = "none") + guides(color = guide_legend( override.aes = list(size = 3), # 设置图例线条粗细(推荐3-5区间) keywidth = unit(2, "cm"), # 加宽图例key区域,让粗线条更清晰 keyheight = unit(0.5, "cm") # 调整key区域高度,优化视觉效果 )) + theme(legend.position = "bottom") + labs(y = "Normalised In-Degree\n")
关键调整说明
- 修正了
dplyr管道符的语法错误(%>改为%>%)。 - 将
override.aes中的size改为合理数值,避免图例区域过度放大。 - 添加
keywidth和keyheight参数,调整图例key的尺寸,让加粗后的线条更易区分。 - 保留了你原本的
size映射逻辑(高亮国家线条更粗),同时确保图例线条的加粗效果清晰呈现。
内容的提问来源于stack exchange,提问作者Djoustaine
相关产品推荐
相关产品推荐

