在ggplot2的geom_smooth中使用最小绝对偏差拟合回归线报错如何解决
报错原因
- 你设置的
method="qr"是错误的:qr是R基础包中用于QR矩阵分解的底层函数,不能直接作为回归拟合方法传入geom_smooth,所以会触发参数无效的报错 - 最小绝对偏差回归等价于分位数为0.5的分位数回归,需要调用你已经加载的
quantreg包的rq()函数实现拟合
解决方案
修改对应geom_smooth图层的参数即可,调整后完整可运行代码如下:
library(quantreg) library(ggplot2) library(data.table) # 你的数据为data.table格式,需加载对应包避免读写报错 data <- structure(list(country_mean_rep = structure(c(73.6995708154506, 93.5501285347044, 85.1529051987768, 91.1017369727047, 79.5562130177515, 84.6751054852321, 89.8, 86.8826405867971, 94.2247191011236, 70.2321428571429, 88.4107142857143), label = "label", format.stata = "%9.2f"), country_mean_crime = c(0.0944206008583691, 0.0565552699228792, 0.0336391437308868, 0.205955334987593, 0.130177514792899, 0.282700421940928, 0.220512820512821, 0.415647921760391, 0.387640449438202, 0.200892857142857, 0.292207792207792), country_name = structure(c(1L, 2L, 3L, 4L, 5L, 7L, 11L, 12L, 14L, 16L, 20L), .Label = c("Albania", "Armenia", "Azerbaijan", "Belarus", "Bosnia and Herzegovina", "Brazil", "Bulgaria", "Cambodia", "Chile", "CostaRica", "Croatia", "Czech", "Ecuador", "Estonia", "FYROM", "Georgia", "Germany", "Greece", "Guyana", "Hungary", "Ireland", "Kazakhstan", "Kenya", "Kyrgyzstan", "Latvia", "Lithuania", "Malawi", "Mali", "Moldova", "Philippines", "Poland", "Portugal", "Romania", "Russia", "Senegal", "Serbia&Montenegro", "Slovakia", "Slovenia", "South Africa", "South Korea", "Spain", "SriLanka", "Tajikistan", "Turkey", "Ukraine", "Uzbekistan", "Vietnam"), class = "factor")), row.names = c(NA, -11L), class = c("data.table", "data.frame")) ggplot(data, aes(x=country_mean_rep, y=country_mean_crime)) + geom_point() + geom_smooth(aes(colour="linear", fill="linear"), method="lm", formula=y ~ x) + # 最小绝对偏差回归图层,method改为rq,指定分位数tau=0.5 geom_smooth(aes(colour="least absolute deviation", fill="least absolute deviation"), method="rq", formula=y ~ x, tau = 0.5) + labs(colour="Functional Form", fill="Functional Form") + geom_text(aes(label=country_name), nudge_y=0.02) + theme_bw()
运行时如果出现rq函数的收敛提示属于正常情况,不影响最终拟合结果。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

