我有一个数据框“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”的强度为地图上的县着色。这样做的方法是什么,甚至可能添加一个传奇?非常感谢!