rsc05
rsc05

Reputation: 3820

R: Add legend to line plots in R without using ggplot2 or with using it but using my own legend?

Consider the following code:

T=1
N=50
X=matrix(rnorm(N*4, mean = 0, sd = 1), 4, N)
t=seq(0,T,by=T/N)
t=head(t,-1)
ymax=max(X); ymin=min(X) #bounds for simulated prices

##Plot
led=c() # For ledgend purposes
ymax=max(X); ymin=min(X) #bounds for simulated prices
plot(t,X[1,], t='l', ylim=c(ymin, ymax), col=1, ylab="Price P(t)", xlab="time t")
led=c(led, paste("GBM", 1))
for(i in 2:4){
    lines(t, X[i,], t='l', ylim=c(ymin, ymax), col=i)
    led=c(led, paste("GBM", i))
}
legend(0, 0, legend=led, lty=1:4, cex=0.8)

The outcome would be enter image description here

As you can see the legend is not observed and if they are observed they are of another colour of that of the lines.

How can I make the legend represent the colour without using the ggplot2? And how to use it with my own created legend?

Upvotes: 0

Views: 80

Answers (2)

Jack Brookes
Jack Brookes

Reputation: 3830

The code is incredible unreadable and is not done in a way you would normally plot in R. Here's a tidyverse solution that gets you to the same place.

tmax <- 1 # shouldnt use T as a variable name
N <- 50
X <- matrix(rnorm(N * 4, mean = 0, sd = 1), 4, N)
times <- seq(0, tmax, by = tmax / N) # shouldnt use t as a variable name
times <- head(times, -1)
ymax <- max(X)
ymin <- min(X) #bounds for simulated prices

library(tidyverse)

df <- as.data.frame(t(X)) %>% 
  mutate(time = times) %>% 
  gather(GBM, price, -time) %>% 
  mutate(GBM = gsub("V", "GBM ", GBM))

ggplot(df, aes(x = time, y = price, color = GBM)) +
  geom_line()

enter image description here

Upvotes: 2

Jim Chen
Jim Chen

Reputation: 3739

Just add col argument in legend

T=1
N=50
X=matrix(rnorm(N*4, mean = 0, sd = 1), 4, N)
t=seq(0,T,by=T/N)
t=head(t,-1)
ymax=max(X); ymin=min(X) #bounds for simulated prices

##Plot
led=c() # For ledgend purposes
ymax=max(X); ymin=min(X) #bounds for simulated prices
plot(t,X[1,], t='l', ylim=c(ymin, ymax), col=1, ylab="Price P(t)", xlab="time t")
led=c(led, paste("GBM", 1))
for(i in 2:4){
  lines(t, X[i,], t='l', ylim=c(ymin, ymax), col=i)
  led=c(led, paste("GBM", i))
}
legend(0, 0, legend=led, cex=0.8,col = 1:4, lwd=2.5)

enter image description here

You can also change legend postion:

legend("topleft", legend=led, cex=0.8,col = 1:4,lwd=2.5)

enter image description here

Upvotes: 1

Related Questions