如何在ggplot散点图中显示趋势线?我的代码为何无效?
问题排查与解决
问题根源:你的cohort列是字符类型(geom_smooth(method='lm')需要x轴为数值型变量才能拟合线性回归模型。字符型变量无法参与线性回归的计算,因此趋势线无法生成和显示。
解决方法有两种:
方法一:绘图时临时转换变量类型
在aes()中将cohort转换为数值型,同时可以通过labs()保持x轴标签不变:ggplot(bipoc, aes(x = as.numeric(cohort), y = count)) + geom_point() + geom_smooth(method = 'lm') + theme_classic() + labs(x = "cohort")方法二:提前修改数据框的变量类型
先把cohort列转为数值型,再进行绘图:# 转换cohort为数值型 bipoc$cohort <- as.numeric(bipoc$cohort) # 绘制图形 ggplot(bipoc, aes(x = cohort, y = count)) + geom_point() + geom_smooth(method = 'lm') + theme_classic()
两种方法都能让线性趋势线正常显示,选择哪种取决于你是否需要永久修改数据中的变量类型。
内容的提问来源于stack exchange,提问作者Scott
相关产品推荐
相关产品推荐

