r - 尝试使用 geom_abline 添加图例
问题描述
我有一个数据框,另存为df
,有两列我想绘制的点。另外,我想在情节上绘制两条线,并希望这些线有一个图例。这是我的代码:
ggplot(df, aes(x = x, y = y)) +
geom_point(color = "black", shape = 16, alpha = 1) +
scale_x_continuous(name = "x", limits = c(-5, 5)) +
scale_y_continuous(name = "y", limits = c(-5, 5)) +
geom_abline(intercept = 0, slope = 4/3, linetype = "dashed",
color = "gray40", size = 1, aes(colour = "XNULL")) +
geom_abline(intercept = 0, slope = 0, linetype = "dotted",
color = "gray40", size = 1, aes(colour = "YNULL")) +
scale_color_manual(name = "", values = c("XNULL" = "red", "YNULL" = "blue")) +
theme(panel.background = element_rect(fill = "white"),
panel.border = element_rect(colour = "black", fill = NA, size = 1),
legend.position = "bottom")
但是,当我运行它时,没有出现图例(我想在底部显示图例)。关于我做错了什么的任何建议?我是新手,ggplot2
我在其他论坛上查找的解决方案都没有帮助。
解决方案
从文档中:
这些几何图形的行为与其他几何图形略有不同。您可以通过两种方式提供参数:作为图层函数的参数,或通过美学。如果您使用参数,例如 geom_abline(intercept = 0, slope = 1),那么在幕后,geom 会创建一个仅包含您提供的数据的新数据框。
显然,您必须指定intercept
and slope
inaes
才能正常工作。
library(ggplot2)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point() +
coord_cartesian(xlim = c(0,10), ylim = c(0,10)) +
geom_abline(aes(intercept = 0, slope = 0, color = "X"), linetype = "dotted") +
geom_abline(aes(intercept = 0, slope = 4/3, color = "Y"),linetype = "dashed") +
scale_color_manual(values = c(X = 'grey', Y = 'black'))
由reprex 包于 2020-02-12 创建(v0.3.0)
推荐阅读
- r - 运行循环以改变样本数量
- node.js - 等待 ssh-exec 完成
- php - Laravel 配置文件的 apache2 域名和目录根位置是什么?
- powershell - 在数组中查找字符串 Powershell V2.0
- c# - WPF C# WebView在win 10上不显示任何页面
- python - 将 matplotlib 条形图打印到 txt 文件
- ionic3 - Ionic 3 和 Identity server 4 示例代码
- firebase - 将 Ionic 视频 fileURI 转换为 dataURL,用于 Firebase 上传
- java - 将 jpa (Hibernate) 中的本机 (join) 查询转换为 json
- ios - 文件存在于 iCloud 中,但 query.resultCount = 0