2

I have the following code:

x <- seq(-25,25, by = .01)
plot(x, dunif(x,-10,10), type = 'l', ylab = 'probability', lwd = 2)
lines(x, dnorm(x,0,10), col = 'blue', lwd = 2)
lines(x, dstudent_t(x,4,0,10), col = 'red', lwd = 2)
lines(x, dcauchy(x,0,10), col = 'green', lwd = 2)
legend(1, 95, legend=c("Uniform (-10,10)", "Normal (0,10)", "Student t (4,0,10)", "Cauchy (0, 10)"),
       col=c("black", "red", "blue", "green"), lty=1:2, cex=0.8)

Which yields me the following plot:

Plot

But the legend doesn't show up and I am not sure where the error is.

RazorLazor
  • 71
  • 5

2 Answers2

1

Try

legend(1, 0.05, legend=c("Uniform (-10,10)", "Normal (0,10)", "Student t (4,0,10)", "Cauchy (0, 10)"),
   col=c("black", "red", "blue", "green"), lty=1:2, cex=0.8)

Your y=95 value in the legend call is way outside the y-axis range.

Valeri Voev
  • 1,982
  • 9
  • 25
0

@jay.sf With your suggestion, the legend works! But the line it displays in the legend it sometimes dashed and sometimes not, how can i change it to a simple line for all distributions in the legend? (as for uniform and normal)

x <- seq(-25,25, by = .01)
plot(x, dunif(x,-10,10), type = 'l', ylab = 'probability', lwd = 2)
lines(x, dnorm(x,0,10), col = 'blue', lwd = 2)
lines(x, dstudent_t(x,4,0,10), col = 'red', lwd = 2)
lines(x, dcauchy(x,0,10), col = 'green', lwd = 2)
legend("topleft", legend=c("Uniform (-10,10)", "Normal (0,10)", "Student t (4,0,10)", "Cauchy (0, 10)"),
       col=c("black", "red", "blue", "green"), lty=1:2, cex=0.8)

Plot

edit: worked by putting:

lty=1

One last question. It seems like i cannot just assign the plot like this, as I usually do for ggplot to save it as a PDF. What's the option here?

plot1 <- plot(x, dunif(x,-10,10), type = 'l', ylab = 'probability', lwd = 2)
lines(x, dnorm(x,0,10), col = 'blue', lwd = 2)
lines(x, dstudent_t(x,4,0,10), col = 'red', lwd = 2)
lines(x, dcauchy(x,0,10), col = 'green', lwd = 2)
legend("topleft", legend=c("Uniform (-10,10)", "Normal (0,10)", "Student t (4,0,10)", "Cauchy (0, 10)"),
       col=c("black", "red", "blue", "green"), lty=1, cex=0.8)
RazorLazor
  • 71
  • 5