Reputation: 87
I'm trying to create a pretty simple scatter plot with two data series. I would like to specify the color of each point through a fourth column in the dataframe I'm using. I've got the scatter plot itself close to where I want it, with two different glyphs for the two series, but the colors are not being assigned to the right points. I'm pretty new to R so I'm not sure where to go from here. Any help would be appreciated. Sample data and code attached (can't upload images yet).
Sample Data:
x y group color
0 0 g red
2 -1 g blueviolet
0 -1 g brown
2 -2 g blueviolet
0 -11 g blue
2 -6 g blue
0 1 g coral
0 -2 g blue
2 -1 h blueviolet
0 -1 h brown
2 -2 h blueviolet
0 -11 h blue
2 -6 h blue
0 1 h coral
2 -8 h blue
4 -2 h coral
1 -5 h brown
1 -9 h violet
-2 2 h blue
Sample R code:
ztest=read.table(file="ztest.txt",sep="\t",header=TRUE)
plot(ztest$x,ztest$y,type='n')
points(ztest[ztest$group=="g",]$x,ztest[ztest$group=="g",]$y,col=ztest$color,pch=3,cex=.75)
points(ztest[ztest$group=="h",]$x,ztest[ztest$group=="h",]$y,col=ztest$color,pch=1,cex=1.75)
Upvotes: 2
Views: 4462
Reputation: 26
You seem to be subsetting the points, but not subsetting the colours. Instead of
points(ztest[ztest$group=="g",]$x,ztest[ztest$group=="g",]$y,col=ztest$color, ...
try
points(ztest[ztest$group=="g",]$x,ztest[ztest$group=="g",]$y,col=as.character(ztest[ztest$group=="g",]$color), ....
Hope this helps
Upvotes: 1
Reputation: 5894
The answer is probably that color is being interpreted as a factor when you read it in with read.table. Try
ztest$color <- as.character(ztest$color)
and see if it works.
Or ggplot2 is awesome for this sort of thing. AFter you've done the above, try as an alternative to your approach
library(ggplot2)
qplot(x,y, color=color, shape=group, data=ztest, size=group) +
scale_color_identity(legend=FALSE) +
scale_shape_manual(values=c(3,1)) +
scale_size_manual(values=c(3,6))
Upvotes: 2