buhtz buhtz - 11 months ago 40
R Question

Why is this legend in R not working?

The plot is shown but the legend not.

df = data.frame(Year=c(2012,2013,2014), N=c(61175,52477,48699))
plot(df[,c('Year', 'N')], type='o')
legend(x=1, y=max(df$N), legend=c('a'), pch=1, lty=1)

I would expect it in the upper-left corner of the graphic.


To make your code work, you need

legend(x=min(df$Year), y=max(df$N), legend=c('a'), pch=1, lty=1)

x=1 is outside the range of your x-axis. But of course, you should not place your legend on the top left corner in this case:

enter image description here