【发布时间】:2018-04-11 06:31:22
【问题描述】:
我发现很多其他帖子解释了如何手动更改 ggplot2 生成的图例顺序,我已经尝试了所有建议,但仍然无法找出答案......
在我的情节中,我显示了来自geom_smooth(带有lm 函数)的线性回归线和我使用geom_abline 任意拟合的另一条线。
ggplot(women, aes(x=height, y=weight)) +
geom_point(size=3, shape = 21, color="black") +
geom_smooth(method = "lm", aes(color= "fit2", linetype = "fit2"), lwd=1, se = FALSE, show.legend = F) +
geom_abline(aes(intercept = -100, slope = 3.5, color="fit1", linetype = "fit1")) +
scale_colour_manual(name="Legend", values = c("fit1" = "blue", "fit2" = "red")) +
scale_linetype_manual(name="Legend", values = c("fit1" = "solid", "fit2" = "dashed"))
这会自动生成带有“fit1”和“fit2”的图例,但我希望“fit2”显示在“fit1”上方。很多帖子建议在我的数据框中重新排序数据,比如d$a <- factor(d$a, levels = d$a),但由于我的geom_abline 是任意行,我不能这样做。我试过scale_fill_discrete(breaks=c("fit2","fit1")) 和guides(fill = guide_legend(reverse = TRUE)) 但都没有工作。有没有其他方法可以强制“fit2”显示在“fit1”上方?
【问题讨论】:
-
不相关,但我认为斜率和截距的值超出了图表的限制。尝试
coef(lm(weight ~ height, data = women))以获得正确的值。 -
@neilfws 哦,你是对的,我更改了斜率和截距的值,以便 fit1 线实际显示在图中。感谢您指出这一点!