如何在ggplot坐标轴上高亮特定因子水平(如指定车型)?
给mtcars散点图高亮指定车型的两种方法
方法1:高亮X轴车型名称(加粗彩色)
核心思路是先标记需要高亮的车型,再通过scale_x_discrete自定义轴文本样式:
data(mtcars) library(tidyverse) # 标记需要高亮的车型 mtcars_highlight <- mtcars %>% mutate( cars = rownames(mtcars), is_highlight = cars %in% c("Fiat 128", "Volvo 142E") ) ggplot(mtcars_highlight, aes(x = cars, y = mpg)) + geom_point() + # 自定义X轴文本:高亮车型用红色加粗,其余默认 scale_x_discrete(labels = function(x) { ifelse(x %in% c("Fiat 128", "Volvo 142E"), paste0("**", x, "**"), x) }) + theme( axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1, color = ifelse(mtcars_highlight$is_highlight, "red", "black"), face = ifelse(mtcars_highlight$is_highlight, "bold", "plain")) )
方法2:给目标车型的散点添加圆圈高亮
在原有散点上叠加空心大圆圈,直接突出指定车型:
data(mtcars) library(tidyverse) mtcars %>% mutate(cars = rownames(mtcars)) %>% ggplot(aes(x = cars, y = mpg)) + # 先绘制所有普通散点 geom_point(color = "black", size = 2) + # 叠加高亮车型的空心圆圈 geom_point( data = . %>% filter(cars %in% c("Fiat 128", "Volvo 142E")), aes(x = cars, y = mpg), color = "red", size = 5, shape = 21, # 空心圆圈形状 fill = NA, # 内部透明 stroke = 2 # 圆圈线条粗细 ) + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
如果需要更规整的圆形高亮,可使用ggforce包:
data(mtcars) library(tidyverse) library(ggforce) mtcars %>% mutate(cars = rownames(mtcars)) %>% ggplot(aes(x = cars, y = mpg)) + geom_point() + # 给目标车型添加精准圆形高亮 geom_circle( data = . %>% filter(cars %in% c("Fiat 128", "Volvo 142E")), aes(x0 = as.numeric(factor(cars)), y0 = mpg, r = 0.3), color = "red", size = 1.5, fill = NA ) + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
内容的提问来源于stack exchange,提问作者Marco
相关产品推荐
相关产品推荐

