yan*_*fri 1 plot r legend ggplot2
我有一些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))
Run Code Online (Sandbox Code Playgroud)
我希望标签的"统一线","双重","半"和"更平滑"出现在图例中的"高"和"低"标签下方.
按照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))
Run Code Online (Sandbox Code Playgroud)
此外,我似乎无法手动更改tinetypes:
我知道,我可以简单地选择其他颜色并且会有更少的混淆但是应该可以有一个只包含点和线的点的图例而不是点和线的点和线,或者不是吗?
ggplot2似乎被添加color或linetype之后的困扰所困扰aes.将行添加到图例时,类别的顺序似乎会发生变化.
您可以将字符值映射到未使用的美学,以欺骗ggplot为您制作图例:
ggplot(data=d) +
geom_point(aes(x, y, colour=cat)) +
geom_abline(aes(intercept=0, slope=1, lty='unity line'), col = "red")
Run Code Online (Sandbox Code Playgroud)
使用+ scale_linetype(name = NULL)删除linetype图例标题.