📅  最后修改于: 2023-12-03 15:23:17.226000             🧑  作者: Mango
在 R 语言中,图例非常重要,它可以帮助我们更好地理解数据的意义以及更清晰地展现数据。在这篇文章中,我们将介绍如何在 R 中添加图例。
添加图例的基本语法如下:
legend(x, y = NULL, legend, fill = NULL, col = par("col"), bg = NA, lty, lwd, pch, angle = 45, density = NULL, bty = "o", pt.bg = NA, pt.cex = 1, pt.lwd = par("lwd"), cex = 1, text.width = NULL, text.col = par("col"), merge = do.lines && has.pch, trace =FALSE, plot = TRUE, ncol = 1, horiz = FALSE, title = NULL)
其中,参数的含义如下:
下面是一个用 ggplot2 生成的散点图:
library(ggplot2)
data <- data.frame(x = c(1, 2, 3), y = c(2, 3, 4))
ggplot(data, aes(x, y)) +
geom_point(size = 3, colour = "red") +
labs(title = "Scatter Plot", x = "X-Axis", y = "Y-Axis")
现在我们来添加图例。首先,我们需要添加颜色和文本,如下:
legend("topright",
legend = "data",
col = "red",
pch = 16,
bg = "white")
接着,我们可以为图例添加标题,调整字体大小和位置,如下:
legend("topright",
legend = "data",
col = "red",
pch = 16,
bg = "white",
title = "Data Points",
cex = 0.8)
最后,我们可以使用 ggplot2 提供的主题来美化图例,如下:
ggplot(data, aes(x, y)) +
geom_point(size = 3, colour = "red") +
scale_fill_grey(name = "Data Points", labels = "data") +
theme_classic()