+5 votes
in Programming Languages by (71.8k points)

I am using the R function plot() to generate a plot. The plot has multiple lines. How can I add legends for each of those lines?

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

To add a legend to a plot, you can use the R function legend(). This function supports several arguments:

legend(x, y = NULL, legend, fill = NULL, col = par("col"),
       border = "black", lty, lwd, pch,
       angle = 45, density = NULL, bty = "o", bg = par("bg"),
       box.lwd = par("lwd"), box.lty = par("lty"), box.col = par("fg"),
       pt.bg = NA, cex = 1, pt.cex = cex, pt.lwd = lwd,
       xjust = 0, yjust = 1, x.intersp = 1, y.intersp = 1,
       adj = c(0, 0.5), text.width = NULL, text.col = par("col"),
       text.font = NULL, merge = do.lines && has.pch, trace = FALSE,
       plot = TRUE, ncol = 1, horiz = FALSE, title = NULL,
       inset = 0, xpd, title.col = text.col, title.adj = 0.5,
       seg.len = 2)

 If you do not want to provide x and y coordinates, you can use one of these values of x for the position of the legend in the plot: "top", "topleft", "topright", "bottom", "bottomleft", "bottomright", "left", "right" or "center".

Here is an example:

b2 <- c(6974487.997809264, 6948551.260216873, 6950057.642098087, 6951500.090518491, 6953066.543803036, 6954577.35977558, 6955794.256252246, 6957075.750709421, 6958545.182869695, 6959858.738054434, 6961228.994514443, 6962504.667176491, 6963838.551921962, 6965148.747454571)
b5 <- c(8961888.359885516, 8950476.56716601, 8891988.792274144, 8873384.061769547, 8836011.610218018, 8837719.032388233, 8839425.970574336, 8841263.95332955, 8842982.513135295, 8844615.61313948, 8846296.912900476, 8847984.22146774, 8849609.921480406, 8851272.12376427)
plot(b2, type = "l", col= "blue", ylab = "BIC", xlab = "Cluster_count", xlim = c(0,15))
par(new=TRUE)
plot(b5, type = "l", col= "red", ylab = "BIC", xlab = "Cluster_count", xlim = c(0,15))
legend(x = "topright", legend = c("Cluster count=2", "Cluster count=5"), col = c("blue","red"), lty = 1)

Make sure that the sequence of colors in the legend function matches the plot, otherwise, you will get the wrong color for legends.

Related questions

+3 votes
1 answer
+5 votes
1 answer
+5 votes
1 answer
asked Sep 25, 2021 in Programming Languages by kush (40.5k points)
+3 votes
1 answer

...