This question is related to the one I asked here. I’m trying to color individual points in a scatterplot with a color specified in a column of the dataframe. The data is from a tab delimited file and looks like this:
> dput(ztestHSV)
structure(list(y = c(0, -1, -1, -2), x = c(0, 2, 0, -2), group = c("m",
"m", "m", "s"), colorHSV = c("0.02,0.83,0.89", "0.59,0.59,0.85",
"0.25,0.45,0.8", "0.55,0.41,0.8"), colorText = c("red", "blue",
"green", "turquoise")), .Names = c("y", "x", "group", "colorHSV",
"colorText"), class = "data.frame", row.names = c(NA, -4L))
i.e.
y x group colorHSV colorText
1 0 0 m 0.02,0.83,0.89 red
2 -1 2 m 0.59,0.59,0.85 blue
3 -1 0 m 0.25,0.45,0.8 green
4 -2 -2 s 0.55,0.41,0.8 turquoise
The following code works well for the predefined set of colors available in R:
ztestHSV=read.table(file="testHSV.txt",sep="\t",header=TRUE,
colClasses=c("numeric","numeric","character","character","character"))
plot(ztestHSV[ztestHSV$group=='m',]$x,ztestHSV[ztestHSV$group=='m',]$y,type='n')
points(ztestHSV[ztestHSV$group=='m',]$x,ztestHSV[ztestHSV$group=='m',]$y,
pch=23,cex=1.5,
bg=ztestHSV[ztestHSV$group=='m',]$colorText
)
What I would really like to do is use hsv() to specify the colors. But I can’t figure out the right bg command to make it work. I’ve tried several things and listed them below with the associated result.
1
bg=hsv(as.numeric(ztestHSV$colorHSV))
Error in hsv(as.numeric(ztestHSV$colorHSV)) :
bad hsv to rgb color conversion
In addition: Warning message:
In hsv(as.numeric(ztestHSV$colorHSV)) : NAs introduced by coercion
2
bg=hsv(as.numeric(strsplit(ztestHSV$colorHSV,",")))
Error in hsv(as.numeric(strsplit(ztestHSV$colorHSV, ","))) :
(list) object cannot be coerced to type 'double'
3
bg=hsv(unlist(strsplit(ztestHSV$colorHSV,",")))
Above runs but uses the wrong background colors
4
bg=hsv(as.numeric(unlist(strsplit(ztestHSV$colorHSV,","))))
Above doesn’t generate an error but doesn’t fill background colors
It seems like this is a problem with converting the character string of colorHSV to something that hsv() can use, but I don’t know how to do it. Any help would be great.
It helps if you provide an easily reproducible example by using something like
dput()to show the data you are using:You can convert the vector of character strings into a list of numerics, and then use
do.call()to callhsv()on each one, like this: