0

我有一个数据框“mydata.final”(见下文),其中包含美国县和一个连续数值变量“Mean.Wait”,范围从零到 10 左右。我还创建了基于 'Mean.Wait' 的变量 'wait',并采用从 1('Mean.Wait' 的最低值)到 5('Mean.Wait' 的最高值)的离散值。

我可以使用 R 包 'maps' 根据'wait' 的值创建美国的地图,其中县有颜色:

######################################################################
### Generating an artificial data file:
######################################################################

library(maps)
mydata.final <- data.frame(county = (map('county', plot = FALSE)$names),
                 stringsAsFactors = F)

### My numeric variable:
set.seed(123)
mydata.final$Mean.Wait <- runif(nrow(mydata.final)) * 10

### Introducing NAs to mimic my real data set:
set.seed(1234)
mydata.final$Mean.Wait[sample(1:nrow(mydata.final), 1500)] <- NA

### Cutting the original numeric variable into categories
### because I don't know how to color based on 'Mean.Wait':
mydata.final$wait <- cut(mydata.final$Mean.Wait, breaks = 5)
levels(mydata.final$wait) <- 1:5
mydata.final$wait <- as.numeric(as.character(mydata.final$wait))

######################################################################
### Building a US map based on 'wait' (5 categories)
######################################################################

### Creating my 5 colors:
pal <- colorRampPalette(c("yellow", "red"))
allcolors <- pal(5)

### Looking at my 5 colors:
barplot(1:5, rep(1,5), col = allcolors, horiz = T)

### Builiding the US map using 5 categories in 'wait':
map('county', fill = TRUE, col = allcolors[mydata.final$wait],
            resolution = 0, lty = 0, bg = "transparent")
map('state', lwd=1, add=TRUE)

我的目标是:我不想将“Mean.Wait”分成 5 个有序类别(“等待”),而是根据我的(连续)“Mean.Wait”的强度为地图上的县着色。这样做的方法是什么,甚至可能添加一个传奇?非常感谢!

4

1 回答 1

0

你在 4 月 2 日也在 R-help 上问过这个问题。以下是答案。

您可以使用colorRamp()andrgb()来获得更连续的颜色。例如

newpal <- colorRamp(c("yellow", "red"))
missing <- is.na(mydata.final$Mean.Wait)
newcol <- ifelse(missing, "white",

rgb(newpal(mydata.final$Mean.Wait[!is.na(mydata.final$Mean.Wait)]/
                                  max(mydata.final$Mean.Wait,
na.rm=T)), maxColorValue=255))
map('county', fill=TRUE, col=newcol,
    resolution=0, lty=0, bg="transparent")
map('state', lwd=1, add=TRUE)

您也可以尝试 plotrix 中的 color.scale 函数,它允许您在调用中指定 NA 颜色。

library(plotrix)   newcol<-color.scale(mydata.final$Mean.Wait,extremes=c("yellow","red"),na.color="white")
于 2015-04-03T11:56:06.750 回答