Wutruvic
Wutruvic

Reputation: 83

Transform the shape and colors of legend in scatterplot in base R

I am trying to make this scatterplot in base R: https://i.sstatic.net/qdgGN.png

This scatterplot is based on the mtcars data.

Now I tried this, however I cannot get the same legend. How can I transform the squares into dots? How do I get the exact same colors? How do I know which format the legend is?

This is my code:

cols = c("deepskyblue", "magenta", "gray50")
plot(mpg ~ wt, xlab="Weight (1000lbs)", ylab="Miles / gallon", col = cyl, pch = 19, data=mtcars)
legend(x = "topright",
       title = "Number of cylinders",
       horiz = TRUE,
       legend = c("4", "6", "8"), 
       bty = 'n',
       cex = 0.7,
       fill = cols)

By the way: I made cols for now, but I think there is another way to solve it.

Thanks in advance!

Upvotes: 0

Views: 760

Answers (1)

Yacine Hajji
Yacine Hajji

Reputation: 1489

"Fill" means that squares with be filled by a colour.
What you need is to use the "pch" argument instead, so you can add the "col" argument to chose for your dots colors.
For info, pch corresponds to the shape you want to chose in your legend.
https://www.r-bloggers.com/2021/06/r-plot-pch-symbols-different-point-shapes-in-r/

Replace

fill=cols

by

col = cols,
pch=19)

Full code:

cols = c("deepskyblue", "magenta", "gray50")
plot(mpg ~ wt, xlab="Weight (1000lbs)", ylab="Miles / gallon", col = cyl, pch = 19, data=mtcars)
legend(x = "topright",
       title = "Number of cylinders",
       horiz = TRUE,
       legend = c("4", "6", "8"), 
       bty = 'n',
       cex = 0.7,
       col = cols,
       pch=19)

If you want to use different colors, then you can chose among the following ones. http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf

Upvotes: 1

Related Questions