根据表中的行位置显示点颜色

时间:2015-09-23 20:22:09

标签: r csv ggplot2 colorbrewer

我想用ggplot2显示csv表中点的散点图。诀窍在于我喜欢每个点或交叉,根据csv文件中的行号(使用RColorBrewer的光谱颜色)来获得不同的颜色。

enter image description here

数据集(dat)如下所示:

       modu mnc       eff
1 0.3080473   0 0.4420544
2 0.3110355   4 0.4633741
3 0.3334024   9 0.4653061

所以我喜欢第1行非常蓝,第2行要少一点,第3行要绿色等等。

到目前为止,这是我的代码:

library(ggplot2)
library(RColorBrewer)

dat <- structure(list(modu = c(0.30947265625, 0.3094921875, 0.32958984375, 
0.33974609375, 0.33767578125, 0.3243359375, 0.33513671875, 0.3076171875, 
0.3203125, 0.3205078125, 0.3220703125, 0.28994140625, 0.31181640625, 
0.352421875, 0.31978515625, 0.29642578125, 0.34982421875, 0.3289453125, 
0.30802734375, 0.31185546875, 0.3472265625, 0.303828125, 0.32279296875, 
0.3165234375, 0.311328125, 0.33640625, 0.3140234375, 0.33515625, 
0.34314453125, 0.33869140625), mnc = c(15, 9, 6, 0, 10, 12, 14, 
9, 5, 11, 0, 15, 0, 2, 14, 13, 14, 17, 11, 12, 13, 6, 4, 0, 13, 
7, 10, 12, 7, 13), eff = c(0.492448979591836, 0.49687074829932, 
0.49421768707483, 0.478571428571428, 0.493537414965986, 0.493809523809524, 
0.49891156462585, 0.499319727891156, 0.495102040816327, 0.492285714285714, 
0.482312925170068, 0.498911564625851, 0.479931972789116, 0.492857142857143, 
0.495238095238095, 0.49891156462585, 0.49530612244898, 0.495850340136055, 
0.50156462585034, 0.496, 0.492897959183673, 0.487959183673469, 
0.495605442176871, 0.47795918367347, 0.501360544217687, 0.497850340136054, 
0.493496598639456, 0.493741496598639, 0.496734693877551, 0.499659863945578
)), .Names = c("modu", "mnc", "eff"), row.names = c(NA, 30L), class = "data.frame")

dat2 <- structure(list(modu = c(0.26541015625, 0.282734375, 0.28541015625, 
0.29216796875, 0.293671875), mnc = c(0.16, 0.28, 0.28, 0.28, 
0.28), eff = c(0.503877551020408, 0.504149659863946, 0.504625850340136, 
0.505714285714286, 0.508503401360544)), .Names = c("modu", "mnc", 
"eff"), row.names = c(NA, 5L), class = "data.frame")

dat$modu = dat$modu
dat$mnc = dat$mnc*50
dat$eff = dat$eff

dat2$modu = dat2$modu
dat2$mnc = dat2$mnc*50
dat2$eff = dat2$eff

res <- do.call(rbind, combn(1:3, 2, function(ii)
        cbind(setNames(dat[,c(ii, setdiff(1:3, ii))], c("x", "y")),
              var=paste(names(dat)[ii], collapse="/")), simplify=F))

ggplot(res, aes(x=x, y=y))+ geom_point(shape=4) +
  facet_wrap(~ var, scales="free")

我该怎么做呢?

谢谢!

1 个答案:

答案 0 :(得分:1)

res <- do.call(rbind, combn(1:3, 2, function(ii)
  cbind(row=seq(nrow(dat)),setNames(dat[,c(ii, setdiff(1:3, ii))], c("x", "y")),
        var=paste(names(dat)[ii], collapse="/")), simplify=F))

ggplot(res, aes(x=x, y=y, color=row))+ geom_point(shape=4) +
  scale_color_gradientn(colours=rev(brewer.pal(10,"Spectral")))+
  facet_wrap(~ var, scales="free")