ggplot绘制直方图加均值标准差线时报object未找到错误如何解决
错误原因
你遇到的报错核心原因是:ggplot 图层中未写在aes()内的参数,不会自动从你指定的west数据框中查找变量。你在geom_vline的xintercept参数中直接写mean(NoHealthInsurance)时,R会默认从全局环境搜索NoHealthInsurance对象,找不到就会抛出对应错误。
解决方法
可以选择以下任意一种方案修改代码:
方案1:直接指定变量所属数据框
在所有用到NoHealthInsurance的位置增加数据框前缀west$即可,修改后代码如下:
hist <- ggplot(data = west) + geom_histogram(aes(NoHealthInsurance), color = wes_palette("Zissou1", 1), fill = wes_palette("Zissou1", 2)[2]) + geom_vline(xintercept = mean(west$NoHealthInsurance)) + geom_vline(xintercept = mean(west$NoHealthInsurance) - sd(west$NoHealthInsurance), color = "blue") + geom_vline(xintercept = mean(west$NoHealthInsurance) + sd(west$NoHealthInsurance), color = "blue") + geom_vline(xintercept = mean(west$NoHealthInsurance) - 2*sd(west$NoHealthInsurance), color = "red", linetype = "dotted") + geom_vline(xintercept = mean(west$NoHealthInsurance) + 2*sd(west$NoHealthInsurance), color = "red", linetype = "dotted")
方案2:提前计算统计量(更推荐,代码更整洁易维护)
先将均值、标准差提前计算存储为变量,再传入绘图参数,避免重复计算:
# 提前计算均值和标准差 mu <- mean(west$NoHealthInsurance) sigma <- sd(west$NoHealthInsurance) hist <- ggplot(data = west) + geom_histogram(aes(NoHealthInsurance), color = wes_palette("Zissou1", 1), fill = wes_palette("Zissou1", 2)[2]) + geom_vline(xintercept = mu) + geom_vline(xintercept = mu - sigma, color = "blue") + geom_vline(xintercept = mu + sigma, color = "blue") + geom_vline(xintercept = mu - 2*sigma, color = "red", linetype = "dotted") + geom_vline(xintercept = mu + 2*sigma, color = "red", linetype = "dotted")
内容的提问来源于stack exchange,提问作者Naurica
相关产品推荐
相关产品推荐

