如何使用Setnames

时间:2016-11-04 03:14:02

标签: r plot colors colorbrewer

我有以下数据框:

dat <- structure(list(TPR = c(0.081, 0.945, 0.953, 0.984, 0.956, 0.031
), FPR = c(0.081, 0.545, 0.606, 0.869, 0.636, 0.01), Classifier = structure(c(1L,
3L, 3L, 3L, 3L, 4L), .Label = c("Luck", "NN", "RF", "SVM"), class = "factor"),
    Mean_AUC = c(0.5, 0.91, 0.91, 0.91, 0.91, 0.764), Classifier_with_mean_AUC = c("Luck(0.500)",
    "RF(0.910)", "RF(0.910)", "RF(0.910)", "RF(0.910)", "SVM(0.764)"
    )), .Names = c("TPR", "FPR", "Classifier", "Mean_AUC", "Classifier_with_mean_AUC"
), row.names = c(309L, 155L, 161L, 187L, 164L, 2L), class = "data.frame")

看起来像这样:

      TPR   FPR Classifier Mean_AUC Classifier_with_mean_AUC
309 0.081 0.081       Luck    0.500              Luck(0.500)
155 0.945 0.545         RF    0.910                RF(0.910)
161 0.953 0.606         RF    0.910                RF(0.910)
187 0.984 0.869         RF    0.910                RF(0.910)
164 0.956 0.636         RF    0.910                RF(0.910)
2   0.031 0.010        SVM    0.764               SVM(0.764)

我想要做的是确定Classifier_with_mean_AUC的相应颜色。

library(RColorBrewer)
colors = brewer.pal(7, "Dark2")[1:7]
colors<-setNames(colors[1:nlevels(dat$Classifier_with_mean_AUC)], levels(dat$Classifier_with_mean_AUC))
colors

在该代码的末尾,它只生成一种颜色#1B9E77,我希望它能产生3种颜色。怎么能正确地做到?

我希望它能产生这样的东西。

Luck(0.500)      RF(0.910)       SVM(0.764)
"#1B9E77"        "#D95F02"       "#7570B3" 

1 个答案:

答案 0 :(得分:0)

levels,您需要使用因子。目前,您的Classifier_with_mean_AUC是一个字符列。

library(RColorBrewer)
colors = brewer.pal(7, "Dark2")[1:7]

## using character values
setNames(colors[1:NROW(unique(dat$Classifier_with_mean_AUC))], unique(dat$Classifier_with_mean_AUC))
# Luck(0.500)   RF(0.910)  SVM(0.764) 
#  "#1B9E77"   "#D95F02"   "#7570B3" 

## to use levels, convert your column to factor
dat$Classifier_with_mean_AUC <- as.factor(dat$Classifier_with_mean_AUC)
setNames(colors[1:nlevels(dat$Classifier_with_mean_AUC)], levels(dat$Classifier_with_mean_AUC))
# Luck(0.500)   RF(0.910)  SVM(0.764) 
#  "#1B9E77"   "#D95F02"   "#7570B3"