如何在不使用y美学的情况下平滑geom_line+count绘制的折线图线条?
如何平滑geom_line(stat="count")生成的折线图?
你希望保留geom_line搭配stat="count"的计数逻辑,同时实现线条平滑,这里有两种基于现有代码的修改方案:
方案1:直接用geom_smooth替代geom_line(保留stat="count")
geom_smooth支持指定stat="count",会自动按x和分组变量计算计数,再对结果做平滑拟合,完全符合你的需求:
set.seed(42) # 模拟数据 years <- seq(2003, 2021, 1) types <- sample(c('A', 'B', 'C'), 730000, replace = TRUE) df <- data.frame( year = sample(years, 730000, replace = TRUE), Type = types ) # 平滑折线图代码 ggplot(df, aes(x = year, group = Type, color = Type)) + geom_smooth(stat = "count", method = "loess", size = 1, se = FALSE) + scale_color_manual(values = c("A" = "#99b1c9", "B" = "#ff7933", "C" = "#9a6aba")) + labs(title = "", x = "", y = "count") + theme_light() + theme(axis.text.x = element_text(color = 'black', face = 'plain', angle = 45, hjust = 1)) + guides(color = guide_legend(title = NULL))
method="loess":适合中小跨度的连续数据(这里年份跨度19年,效果合适);如果需要更稳定的平滑,可改用method="gam"并配合公式formula = y ~ s(x)se=FALSE:关闭置信区间显示,若需要保留可删除该参数span参数:可调整平滑程度,比如span=0.5会更贴近原始数据,span=1线条更平滑
方案2:保留原折线+叠加平滑线
如果需要同时展示原始计数折线和平滑线,可叠加geom_line和geom_smooth:
ggplot(df, aes(x = year, group = Type, color = Type)) + geom_line(stat = "count", size = 1, alpha = 0.3) + # 原始折线设半透明,避免遮挡平滑线 geom_smooth(stat = "count", method = "loess", size = 1, se = FALSE) + scale_color_manual(values = c("A" = "#99b1c9", "B" = "#ff7933", "C" = "#9a6aba")) + labs(title = "", x = "", y = "count") + theme_light() + theme(axis.text.x = element_text(color = 'black', face = 'plain', angle = 45, hjust = 1)) + guides(color = guide_legend(title = NULL))
注意
你原代码中的变量名(Year、var1)和模拟数据中的变量名(year、Type)不一致,需要统一后代码才能正常运行。
内容的提问来源于stack exchange,提问作者Espejito
相关产品推荐
相关产品推荐

