How to change colors according to the species in the iris dataset?

If I use the following code, I get dots with different random colors. How can I be the one who chooses the colors?

plot(iris$Sepal.Length, iris$Petal.Length, col = iris$Species)
Original post in Spanish

Si coloco el siguiente código, me aparecen los puntos con diferentes colores al azar. Cómo puedo ser yo quien elija los colores?

Hi Cesar! Welcome to the community!

Can I please request you to translate your question into English? There are not many people here who will understand Spanish, and hence translating will really improve your chances of getting help?

Based on what I understood from Google translate, I think you're misunderstanding. The colours are not random. You've supplied iris$Species as colour, and R detects that it is a factor variable with 3 levels. So, after plotting the points, it colours them with the 1st 3 colours in the current colour palette, which are "black", "red" and "green3" unless you change it.

If you want to change the colours as you wish, you can take a look at palette function. You can specify a vector of colours and that will become the palette. For any plot, it'll start from the first colour of the palette, and continue. If the palette ends, it'll start back at the first colour.

# checking default colour palette
palette()
#> [1] "black"   "red"     "green3"  "blue"    "cyan"    "magenta" "yellow" 
#> [8] "gray"

# changing palette
palette(value = c("rosybrown3", "darkorchid3", "darkolivegreen4"))

# current colour palette
palette()
#> [1] "rosybrown3"      "darkorchid3"     "darkolivegreen4"

Created on 2019-09-21 by the reprex package (v0.3.0)

Hope this helps.

1 Like

Hi Cesar,
As Yarnabrina said, English is the preferred language here, If you have problems with English and need help in Spanish, feel free to contact me via DM. I hope you don't minde I that had translated your post


Hola cesar
Como dijo Yarnabrina, el inglés es el idioma preferido aquí. Si tiene problemas con el inglés y necesita ayuda en español, no dudes en comunicarte conmigo a través de un mensaje directo. Espero que no te importe que haya traducido tu publicación.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.