0

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

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

IE

   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()可以使用的东西的问题,但我不知道该怎么做。任何帮助都会很棒。

4

2 回答 2

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)
于 2012-06-11T03:54:59.700 回答
0

您只需要将一列拆分为三个单独的列,然后将每个列传递给hsv. 最方便的方法(据我所知)是使用colsplitfrom reshape2

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

然后你可以将它们分配给bg并绘制。请注意,这节省了相当多的输入,并且必须处理将值显式强制转换为数字。

于 2012-06-11T03:55:42.107 回答