Colouring plot by factor in R

后端 未结 6 1560
执念已碎
执念已碎 2020-12-02 15:21

I am making a scatter plot of two variables and would like to colour the points by a factor variable. Here is some reproducible code:

data <- iris
plot(da         


        
6条回答
  •  醉梦人生
    2020-12-02 16:16

    The command palette tells you the colours and their order when col = somefactor. It can also be used to set the colours as well.

    palette()
    [1] "black"   "red"     "green3"  "blue"    "cyan"    "magenta" "yellow"  "gray"   
    

    In order to see that in your graph you could use a legend.

    legend('topright', legend = levels(iris$Species), col = 1:3, cex = 0.8, pch = 1)
    

    You'll notice that I only specified the new colours with 3 numbers. This will work like using a factor. I could have used the factor originally used to colour the points as well. This would make everything logically flow together... but I just wanted to show you can use a variety of things.

    You could also be specific about the colours. Try ?rainbow for starters and go from there. You can specify your own or have R do it for you. As long as you use the same method for each you're OK.

提交回复
热议问题