简体   繁体   English

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

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

I'm trying to map an outcome measured at the county-level in Idaho.我正在尝试绘制在爱达荷州县级测量的结果。 I'm not understanding the error message below.我不明白下面的错误信息。 The following code reproduces the error.以下代码重现了该错误。 I've tried limiting map.data to just one row per county, but this also results in an error.我尝试将 map.data 限制为每个县仅一行,但这也会导致错误。

require(usmap)
require(ggplot2)

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

random outcome values for plotting by county按县绘制的随机结果值

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

merge to add "values" variable to map.data合并以将“值”变量添加到 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 error:错误:

This is the R error I get:这是我得到的 R 错误:

Don't know how to automatically pick scale for object of type data.frame.不知道如何为 data.frame 类型的对象自动选择比例。 Defaulting to continuous.默认为连续。
Error: Aesthetics must be either length 1 or the same as the data (35884): fill错误:Aesthetics 必须是长度为 1 或与数据相同 (35884):填充

Next, I planned to color the counties based on the "values" using the following:接下来,我计划使用以下内容根据“值”为县着色:

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

Apparently, the problem comes from the name of the second column of your dataframe, that you called "values".显然,问题来自数据框第二列的名称,您称之为“值”。 Maybe plot_usmap breaks when the argument values calls a column called values .当参数values调用名为values的列时,可能plot_usmap会中断。

Your code works when the name of that column is "X" for example:例如,当该列的名称为“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") 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM