如何在ggplot折线图中仅降低指定线条的透明度?
解决ggplot中仅让部分线条透明的问题
要实现仅降低灰色线条透明度、保留彩色线条鲜艳度的效果,有两种简单可行的方法:
方案一:分两次绘制线条(推荐)
将数据拆分为「重点县(彩色线条)」和「其他县(灰色线条)」两部分,分别调用geom_line并设置不同的透明度,直观控制每类线条的样式:
ggplot() + # 先绘制所有非重点县的灰色线条,设置低透明度 geom_line( data = IRL_counties_Covid19[!IRL_counties_Covid19$CountyName %in% c("Galway", "Dublin", "Leitrim"), ], aes(x=TimeStamp, y=ConfirmedC, group=CountyName), color = "grey", size=1.5, alpha = 0.1 ) + # 再绘制三个重点县的彩色线条,保留全透明度 geom_line( data = IRL_counties_Covid19[IRL_counties_Covid19$CountyName %in% c("Galway", "Dublin", "Leitrim"), ], aes(x=TimeStamp, y=ConfirmedC, color=CountyName), size=1.5, alpha = 1 ) + xlab("Date") + ylab("Cumulative Cases") + scale_y_continuous(labels = scales::comma, breaks = seq(0, 250000, 25000)) + scale_x_date(date_labels = "%b %Y", date_breaks = "1 month") + theme_bw() + theme(legend.position = "bottom") + scale_color_manual(values = c("Galway" = "orange", "Dublin" = "green", "Leitrim" = "purple")) + guides(color = guide_legend(override.aes = list(size = 3))) + ggtitle("Cumulative COVID-19 Cases by County in Ireland (Sep 2021 - Mar 2023)")
说明
- 先画灰色线条、再画彩色线条,能保证彩色线条显示在上方,避免被灰色线条遮挡
- 无需修改原始数据,逻辑清晰,新手易上手
方案二:通过映射alpha参数实现
给原始数据新增一列标记「是否为重点县」,将alpha映射到该列,再手动设置透明度值:
# 第一步:给数据新增分类列 IRL_counties_Covid19 <- IRL_counties_Covid19 %>% mutate(is_highlight = ifelse(CountyName %in% c("Galway", "Dublin", "Leitrim"), "highlight", "other")) # 第二步:绘图并映射alpha ggplot(IRL_counties_Covid19, aes(x=TimeStamp, y=ConfirmedC, group=CountyName, color=CountyName, alpha=is_highlight)) + geom_line(size=1.5) + xlab("Date") + ylab("Cumulative Cases") + scale_y_continuous(labels = scales::comma, breaks = seq(0, 250000, 25000)) + scale_x_date(date_labels = "%b %Y", date_breaks = "1 month") + theme_bw() + theme(legend.position = "bottom") + # 修正颜色映射:灰色数量应为总县数减3(3个彩色县) scale_color_manual( values = c("Galway" = "orange", "Dublin" = "green", "Leitrim" = "purple", rep("grey", length(unique(IRL_counties_Covid19$CountyName))-3)), breaks = c("Galway", "Dublin", "Leitrim") ) + # 设置透明度映射,隐藏alpha图例避免干扰 scale_alpha_manual(values = c("highlight" = 1, "other" = 0.1), guide = "none") + guides(color = guide_legend(override.aes = list(size = 3))) + ggtitle("Cumulative COVID-19 Cases by County in Ireland (Sep 2021 - Mar 2023)")
说明
- 适合需要对数据进行更多分类处理的场景
- 注意修正
scale_color_manual中灰色的数量,避免颜色不匹配
内容的提问来源于stack exchange,提问作者Joseph Linane
相关产品推荐
相关产品推荐

