尝试按结果变量为县着色时 R plot_usmap() 中的错误

error in R plot_usmap() when trying to color counties by outcome variable

我正在尝试绘制在爱达荷州县级测量的结果。我不明白下面的错误信息。以下代码重现了该错误。我试过将 map.data 每个县限制为一行,但这也会导致错误。

require(usmap)
require(ggplot2)

map.data <- usmap::us_map("counties",
                          include = "ID")
dim(map.data)
1090   10

按县绘制的随机结果值

n.county <- length(unique(map.data$fips))
set.seed(0)
d <- data.frame( fips = unique(map.data$fips),
                 values = runif(n.county))
head(d)
    fips    values
 1 16001 0.8966972
 2 16003 0.2655087
 3 16005 0.3721239
 4 16007 0.5728534
 5 16009 0.9082078
 6 16011 0.2016819

合并以将 "values" 变量添加到 map.data

map.data <- merge( map.data, d)
map.data <- map.data[ , c("fips", "values")]
dim(map.data)
1090   2

plot_usmap( regions = "counties",
            include = "ID", 
            data = map.data,
            values = "values") + 
  labs( title = "Idaho",
        subtitle = "Outcome Y") 

R错误:

这是我得到的 R 错误:

Don't know how to automatically pick scale for object of type data.frame. Defaulting to continuous.
Error: Aesthetics must be either length 1 or the same as the data (35884): fill

接下来,我计划使用以下方法根据 "values" 为县上色:

  + scale_fill_continuous( low = "white", 
                           high = "red", 
                           name = "Legend", 
                           label = scales::comma) + 
  theme( legend.position = "right")

显然,问题出在数据框第二列的名称上,您称之为 "values"。当参数 values 调用名为 values.

的列时,可能 plot_usmap 中断

当该列的名称为 "X" 时,您的代码有效,例如:

require(usmap)
require(ggplot2)

map.data <- usmap::us_map("counties", include = "ID")
dim(map.data)
n.county <- length(unique(map.data$fips))
set.seed(0)
d <- data.frame( fips = unique(map.data$fips),
                 X = runif(n.county))
head(d)

map.data <- merge( map.data, d)
map.data <- map.data[ , c("fips", "X")]
dim(map.data)
1090   2

plot_usmap( regions = "counties",
            include = "ID", 
            data = map.data,
            values = "X") + 
  labs( title = "Idaho",
        subtitle = "Outcome Y")