使用hsv()中数据框的逗号分隔值

时间:2012-06-11 03:41:12

标签: r

这个问题与我提到的那个here有关。我正在尝试使用数据框的列中指定的颜色为散点图中的各个点着色。数据来自制表符分隔文件,如下所示:

> 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))

   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

以下代码适用于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
)

我真正想做的是使用hsv()来指定颜色。但是我找不到合适的bg命令来使它工作。我已经尝试了几件事,并在下面列出了相关的结果。

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,",")))

以上运行但使用了错误的背景颜色

4

bg=hsv(as.numeric(unlist(strsplit(ztestHSV$colorHSV,","))))

以上不会产生错误但不会填充背景颜色

将colorHSV的字符串转换为hsv()可以使用的字符似乎是个问题,但我不知道该怎么做。任何帮助都会很棒。

2 个答案:

答案 0 :(得分:1)

如果您通过使用dput()之类的内容来显示您正在使用的数据,则可以提供易于重现的示例:

> dput(ztestHSV)
structure(list(y = c(0L, -1L, -1L, -2L), x = c(0L, 2L, 0L, -2L
), group = structure(c(1L, 1L, 1L, 2L), .Label = c("m", "s"), class = "factor"), 
    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 = structure(c(3L, 1L, 2L, 4L), .Label = c("blue", 
    "green", "red", "turquoise"), class = "factor")), .Names = c("y", 
"x", "group", "colorHSV", "colorText"), row.names = c(NA, -4L
), class = "data.frame")

您可以将字符串向量转换为数字列表,然后使用do.call()在每个字符串上调用hsv(),如下所示:

> bg <- sapply(strsplit(ztestHSV$colorHSV, ","), function(x) do.call(hsv, as.list(as.numeric(x))))
> dput(bg)
c("#E33D27", "#5994D9", "#9ECC70", "#78B3CC")
> plot(1:4, pch = 21, cex = 20, bg = bg)

答案 1 :(得分:0)

您只需要将这一列拆分为三个单独的列,然后将每个列传递给hsv。最明智的方法(我知道)是使用 reshape2 中的colsplit

> hsvCols <- reshape2::colsplit(ztestHSV$colorHSV,",",names = c('h','s','v'))
> with(hsvCols,hsv(h,s,v))
[1] "#E33D27" "#5994D9" "#9ECC70" "#78B3CC"

然后你可以将它们分配给bg并绘制。请注意,这样可以节省大量的输入,并且必须处理明确地将值强制转换为数字。