如何将颜色设置为相应的值

时间:2015-12-11 13:35:59

标签: r

颜色的分布应该根据值。

示例:

colour.palette <- colorRampPalette(c("darkgreen","yellow","red"), space = "rgb")

par(mfrow=c(1,2))
x1 <- c(0.1,0.2,0.3,0.4,0.5,0.6,0.65,0.70,0.725,0.750,0.775,0.80,0.825,0.85,0.875,0.9,1)
x2 <- c(0.01,0.02,0.03,0.04,0.05,0.06,0.065,0.070,0.225,0.350,0.475,0.50)
barplot(as.matrix(x1), horiz=FALSE, col=colour.palette(length(x1)))
barplot(as.matrix(x2), horiz=FALSE, col=colour.palette(length(x2)))

enter image description here

x2颜色分布的条形图应该是黄色而不是红色。对应于red颜色的值是约值。从0.8到1.

那么如何修改这个采用任何矢量长度和绘制颜色以匹配0-1间隔的示例? 0-1区间内最多可能有150个数据点。感谢。

1 个答案:

答案 0 :(得分:1)

肯定有一种更简单的方法,但您可以做的是将数据分组并创建匹配的因子标签。我用过你的数据。

# binning
x1b <- .bincode(x1,seq(0,1,0.1),T)
x2b <- .bincode(x2,seq(0,1,0.1),T)
# which "factor levels" also appear in the second vector?
a <- intersect(x2b,x1b)
# set factor labels
x1bf <- factor(x1b, labels = colour.palette(length(seq(0,1,0.1))-1))
x2bf <- factor(x2b, labels = colour.palette(length(seq(0,1,0.1))-1)[a])
# plot
par(mfrow=c(1,2))
barplot(as.matrix(x1), horiz=FALSE, col=as.character(x1bf))
barplot(as.matrix(x2), horiz=FALSE, col=as.character(x2bf)) 

或使用较长向量的长度

x1b <- .bincode(x1,seq(0,1,1/length(x1)),T)
x2b <- .bincode(x2,seq(0,1,1/length(x1)),T)
x1bf <- factor(x1b, labels = colour.palette(length(x1))[unique(x1b)])
x2bf <- factor(x2b, labels = colour.palette(length(x1))[unique(x2b)])