Deividas Kiznis
Deividas Kiznis

Reputation: 451

How to add legend to a plot diagram in R

I have this dataframe made out of col1 and col2 data. What I need is add a legend that shows col2 values.

df <- data.frame(col1 = c( 1, 2, 3,1,2,4,6,6),
             col2 = c( 4, 5, 6,4,5,6,4,6))

     mycolors = c('red','yellow','blue')
plot(df[c("col1", "col2")],col=mycolors)
legend(1, 95,legend=c("col2"),
   col=c("red", "blue"), lty=1:2, cex=0.8)

Upvotes: 1

Views: 239

Answers (1)

tmrlvi
tmrlvi

Reputation: 2361

You had four small mistakes:

  • The location of your legend is outside the grid. Try 4.5,6.0 instead.
  • legend= should be a list of labels, probably unique. Use unique(df$col2)
  • col= should be the same colors. Use col=mycolors
  • You should add the symbol of the dots in the plot. That is - pch=1

To sum up:

legend(4.5, 6.0, legend = unique(df$col2), col=mycolors, pch = 1)

Upvotes: 1

Related Questions