ggplot2中为特定geom_area对应type=3数据添加geom_point的实现方法
解决方法
你只需要为geom_point()图层单独指定筛选后的数据源,即可仅为type等于3的记录绘制散点,不需要修改其他逻辑。
核心修改点
将原代码中全局生效的:
geom_point(size=2)
替换为仅读取type=3子集的版本:
# 直接筛选数据框的写法 geom_point(data = df[type == 3], size=2)
如果希望承接ggplot传入的全局数据,也可以用公式语法糖的写法:
# 适配动态全局数据的写法 geom_point(data = ~ .x[.x$type == 3, ], size=2)
修改后完整代码
library(data.table) library(ggplot2) df <- structure(list(date = c("2021-07-31", "2021-08-31", "2021-09-07", "2021-09-14", "2021-09-21", "2021-09-30", "2021-10-7", "2021-10-14", "2021-10-21", "2021-10-31", "2021-11-30", "2021-12-31", "2022-1-31", "2022-2-28"), value = c(190.3, 174.9, 163.2, 168.4, 168.6, 168.2, 163.5, 161.6, 172.9, 166.5, 175.2, 197.7, 212.1, 177.9), type = c(1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L)), class = "data.frame", row.names = c(NA, -14L)) df$type <- as.factor(df$type) df$date <- as.Date(df$date) setDT(df, key = "date") types.extend <- c(1) new.values <- df[, .SD[1], by = .(type)][, type := shift(type, type = "lag")][type %in% types.extend,] # bind the new value to your original data df <- rbind(df, new.values) ggplot(data = df, aes(x=date, y=value, group=type, color = type, fill = type)) + geom_area(alpha=0.4, position = "identity") + # 仅为type=3的数据添加散点 geom_point(data = df[type == 3], size=2) + scale_color_manual(values=c("1" = "gray", "2" = "red", "3" = "blue"), aesthetics = c("color", "fill"), name = "type") + theme_bw()
原理解释
ggplot2的每个图层都可以单独传入data参数,优先级高于ggplot()中定义的全局数据源。单独为geom_point传入筛选后的type=3子集,就只会为这部分数据渲染散点,不会影响面积图等其他图层的展示效果。
内容的提问来源于stack exchange,提问作者ah bon
相关产品推荐
相关产品推荐

