Different color points in R

Viewed 54

I have the following R-code,

x1=c(3,2,4,1,2,4,4)
x2=c(4,2,4,4,1,3,1)
Y=c("red","red","red","red","blue","blue","blue")
plot(x1,x2,col=Y,pch=8)
grid(NULL,NULL,col="cornsilk2")
legend("right",c("Point","star"),col=c("red","blue"))

That creates a plot as seen below Test image

There are two things that I wish to change however I am not sure how to go about it. 1) I want to change the types of points that appear using the pch feature in plot. So for example, I want the red points to appear as a star and the blue points to appear as a triangle. How would I go about this? 2) I want the legend to show those symbols and be coloured respectively correctly. For example, instead of having "Point" it should be a "." that is coloured blue or red depending on what colour I decide to assign it.

Many thanks for the help.

1 Answers

You specify a vector like your color:

SHAPE = ifelse(Y=="red",8,2)
plot(x1,x2,col=Y,pch=SHAPE)
legend("right",c("Point","star"),col=c("blue","red"),pch=c(2,8))

enter image description here

Related