我有一个散点图,我需要4条引导线。我没有直接使用数据集中的变量来定义绘图脚本中的那些行。 (垂直线是x值的平均值和中值。另外两条线的斜率是1和0.5。)
如何定义线条的颜色并获得正确的图例标签?在我的情节中,颜色和标签混合在一起。
回答的问题here (possibly duplicate)与我上面的问题相似,但我认为并非如此。前一个问题是关于scale_colour - 和scale_fill_manual之间的区别以及包含aes()来获取传奇的重要性,我想。我的问题是关于混合图例标签和颜色,因为我没有在geom_-调用中定义值并且已经将scale_colour_manual()中的值和颜色分开。
我的代码:
library(dplyr)
df <- iris %>%
group_by(Species) %>%
do({
mod = lm(Sepal.Length~Petal.Length, data = .)
data.frame(Intercept = coef(mod)[1],
Slope = coef(mod)[2],
SD= summary(mod)$coefficients[2,2])
})
meanSlope <- mean(df$Slope)
medianSlope <- median(df$Slope)
library(ggplot2)
ggplot(data=df, aes(x=Slope, y=SD)) +
geom_point() +
scale_x_continuous(limits = c(0,1.0)) +
scale_y_continuous(limits = c(0,1.0))+
geom_abline(aes(intercept = 0, slope = 1, colour="red"), show.legend = TRUE) +
geom_abline(aes(intercept = 0, slope = 0.5, colour="blue"), show.legend = TRUE) +
geom_vline(aes(xintercept = meanSlope, colour= "green"), show.legend = TRUE) +
geom_vline(aes(xintercept= medianSlope, colour= "darkgreen"), show.legend = TRUE) +
scale_colour_manual(name="Guide lines", values=c("red", "blue", "green", "darkgreen"),
labels=c("1 SD", "0.5 SD", "mean", "median"))
答案 0 :(得分:3)
尝试映射到行的名称,然后设置颜色:
ggplot(data=df, aes(x=Slope, y=SD)) +
geom_point() +
scale_x_continuous(limits = c(0, 1.0)) +
scale_y_continuous(limits = c(0, 1.0))+
geom_abline(aes(intercept = 0, slope = 1, colour = "1 SD"), show.legend = TRUE) +
geom_abline(aes(intercept = 0, slope = 0.5, colour = "0.5 SD"), show.legend = TRUE) +
geom_vline(aes(xintercept = meanSlope, colour = "mean"), show.legend = TRUE) +
geom_vline(aes(xintercept= medianSlope, colour = "median"), show.legend = TRUE) +
scale_colour_manual(name = "Guide lines",
values = c('1 SD' = "red", '0.5 SD' = "blue",
mean = "green", median = "darkgreen"))