Ggplot2:如何为添加到散点图中的线添加图例? [英] ggplot2: how to add the legend for a line added to a scatter plot?
本文介绍了Ggplot2:如何为添加到散点图中的线添加图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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"、"Twoble"、"Half"和"Smother"标签出现在图例中的"高"和"低"标签下方。
按照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))
另外,我似乎无法手动更改tinetype:
scatter plot with ablines and smoother
我知道,我可以简单地选择其他颜色,这样会减少混淆,但应该可以有一个图例,其中只有点表示点,线表示线,而不是点和线都有点和线,或者不是吗?
ggplot2似乎对在aes
之后添加color
或linetype
感到困扰。向图例添加线条时,类别的顺序似乎已更改。
推荐答案
您只需将一个字符值映射到一个未使用的美感,即可诱使ggploy为您制作图例:
ggplot(data=d) +
geom_point(aes(x, y, colour=cat)) +
geom_abline(aes(intercept=0, slope=1, lty='unity line'), col = "red")
使用+ scale_linetype(name = NULL)
或labs(linetype = NULL)
删除linetype
图例标题。
这篇关于Ggplot2:如何为添加到散点图中的线添加图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文