Joe
Joe

Reputation: 101

Adding a legend to a plot

How to add a legend to the following code that is located outside the plot area. Here is a prodicble code:

par(pty="s")
library(ROCR)
data(ROCR.simple)
pred <- prediction( ROCR.simple$predictions, ROCR.simple$labels )
pred2 <- prediction(abs(ROCR.simple$predictions + 
                    rnorm(length(ROCR.simple$predictions), 0, 0.1)), 
            ROCR.simple$labels)
perf <- performance(pred, "tpr", "fpr" )
perf2 <- performance(pred2, "tpr", "fpr")
# Plot pred 1
plot(perf, col="red")
# plot pred 2
plot(perf2, add = TRUE, col="blue")

Any suggestions would be appreciated. Thank you!

Upvotes: 3

Views: 4333

Answers (1)

G5W
G5W

Reputation: 37631

One way that you can do this is to use par to increase the margin at the top and also to enable writing outside the plot region. Then you can use legend with a negative inset.

## Your graph
par(mar=c(5.1,4.1,6,2.1), xpd=TRUE)
plot(perf, col="red")
plot(perf2, add = TRUE, col="blue")

## Add Legend
legend("topright", c("Pred1", "Pred2"), lty=1, 
    col = c("red", "blue"), bty="n", inset=c(0,-0.15))

Legend in margin

Upvotes: 4

Related Questions