ggplot2重新排序X轴后geom_smooth不显示的问题求助
问题原因
reorder(n, ni)会将原本数值型的n转换为因子类型,而geom_smooth中使用的poly(x,4)要求自变量是连续数值型变量,因子无法被多项式拟合,因此拟合线无法生成。
解决方案
提供两种可行的解决思路:
方案1:提前生成排序后的连续型x变量(推荐)
先在数据集中生成一个按ni排序的连续型位置变量,用它作为拟合的x轴,同时替换刻度标签为原n值,兼顾排序和拟合需求:
# 加载dplyr用于数据处理(未安装先运行install.packages("dplyr")) library(dplyr) # 按Type分组,每组内按ni排序,生成连续的排序位置变量 GGCV <- GGCV %>% group_by(Type) %>% arrange(ni) %>% mutate(x_sorted = row_number()) %>% ungroup() # 绘图代码 p11 <- ggplot(GGCV, aes(x = x_sorted, y = Value, color = Type)) + geom_point(alpha = 0.7, size = 3) + geom_smooth(se = FALSE, method = "lm", formula = y ~ poly(x, 4), size = 1) + labs(x = "Areas, sorted by sample size", title = "Coefficient of Variation %", y = "CV%", color = "Estimator") + scale_color_manual(values = c("#999999", "#E69F00", "#00A550")) + # 将x轴刻度替换为原n值,保持排序后的顺序 scale_x_continuous(breaks = 1:35, labels = GGCV %>% distinct(x_sorted, n) %>% arrange(x_sorted) %>% pull(n)) + coord_cartesian(ylim = c(0, 35)) + theme(legend.position = "none") + scale_y_continuous(labels = scaleFUN)
方案2:在geom_smooth中单独指定连续型x变量
保持散点图的x轴为reorder(n, ni)的因子排序,同时在geom_smooth中手动指定x为连续型的ni(因为reorder(n, ni)的顺序完全对应ni的排序):
p11 <- ggplot(GGCV, aes(x = reorder(n, ni), y = Value, color = Type)) + geom_point(alpha = 0.7, size = 3) + # 单独指定x为连续型的ni,继承color分组进行拟合 geom_smooth(aes(x = ni), se = FALSE, method = "lm", formula = y ~ poly(x, 4), size = 1) + labs(x = "Areas, sorted by sample size", title = "Coefficient of Variation %", y = "CV%", color = "Estimator") + scale_color_manual(values = c("#999999", "#E69F00", "#00A550")) + coord_cartesian(ylim = c(0, 35)) + theme(legend.position = "none") + scale_y_continuous(labels = scaleFUN)
内容的提问来源于stack exchange,提问作者Lorenzo
相关产品推荐
相关产品推荐

