我正在尝试使用以下代码为geom_smooth和geom_abline生成图例
ggplot(data = d, aes(x = log(x), y =log(y) )) +
geom_hex() +
geom_smooth(method='lm',formula=y~x, color = "red", show.legend=TRUE) +
geom_abline(color = "green", show.legend=TRUE) +
scale_colour_manual(name='Lines', values=c("Regression", "Abline"))+
theme_bw()
我在这里看到了一个相关的问题:ggplot2 legend for abline and stat_smooth,但是没有推荐的解决方案产生图例。有任何想法吗?
一些虚假数据:
x <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
y <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
d <- data.frame(x = x, y = y)
编辑:按照卡米尔(Camile)的建议,我在颜色周围添加了aes(),但无济于事。
ggplot(data = d, aes(x = log(x), y =log(y) )) +
geom_hex() +
geom_smooth(method='lm',formula=y~x, aes(color = "red"), show.legend=TRUE) +
geom_abline(aes(color = "green"), show.legend=TRUE) +
scale_colour_manual(name='Lines', values=c("Regression", "Abline"))+
theme_bw()
这适用于geom_smooth线,但是现在geom_abline在说:“错误:geom_abline需要以下缺失的美感:倾斜,截距”
答案 0 :(得分:2)
这是一个选择
ggplot(data = d, aes(x = log(x), y =log(y) )) +
geom_hex() +
geom_smooth(method='lm',formula=y~x, aes(color = "red")) +
geom_abline(aes(slope = 1, intercept = 0, color = "green"), show.legend=FALSE) +
scale_colour_manual(name='Lines',
labels = c("Abline", "Regression"),
values=c("green", "red")) +
theme_bw()
当我们将color
映射到"green"
geom_abline
抱怨的ggplot
时
错误:geom_abline需要以下缺失的美感:倾斜,拦截
这就是为什么我也必须包括这些美学。