【发布时间】:2017-08-09 14:11:26
【问题描述】:
我有一些 x 和 y 数据,我想在 ggplot2 散点图上进行比较。 我想添加一条统一线 (y = x)、双重 (y = 2x)、一半 (y = x/2) 和更平滑的线以帮助理解数据,但我找不到如何将这些线添加到情节的传说。有什么想法吗?
set.seed(123)
x <- runif(20, 1, 10)
y <- 0.8 * x + runif(20, -1, 1)
cat <- factor(c(rep("high", 10), rep("low", 10)))
d <- data.frame(x, y, cat)
ggplot(data=d) +
geom_point(aes(x, y, colour=cat)) +
geom_abline(aes(intercept=0, slope=1), col = "red") +
geom_abline(aes(intercept=0, slope=0.5), col="blue", linetype="dotted") +
geom_abline(aes(intercept=0, slope=2), col="blue", linetype="dashed")+
geom_smooth(aes(x, y))
y vs x scatter plot in ggplot2
我希望标签“unity line”、“twofold”、“half”和“smoother”出现在图例中的“high”和“low”标签下方。
按照 User3640617 的回答,我尝试了以下代码,但结果仍然不令人满意,因为数据点现在在图例中具有与其链接的线型和平滑线型。
ggplot(data=d) +
geom_point(aes(x, y, colour=cat)) +
geom_abline(aes(intercept=0, slope=1, colour="y = x")) +
geom_abline(aes(intercept=0, slope=.5, colour="y = x/2")) +
geom_abline(aes(intercept=0, slope=2, colour="y = 2x")) +
geom_smooth(aes(x,y, colour="smooth")) +
scale_color_manual(
values=c("red", "darkgreen", "black", "blue", "red", "blue")) +
scale_linetype_manual(
values=c("blank", "blank", "solid", "dashed", "solid", "dotted")) +
scale_shape_manual(values=c(1, 1, NA, NA, NA, NA))
另外,我似乎无法手动更改 tinetypes:
scatter plot with ablines and smoother
我知道,我可以简单地选择其他颜色,这样会减少混乱,但应该可以有一个图例,只有点代表点,线代表线,而不是点 和 线代表点和线都行,还是不行?
ggplot2 似乎对在aes 之后添加color 或linetype 感到困扰。将线条添加到图例时,类别的顺序似乎发生了变化。
【问题讨论】: