使用 Choroplethr 将颜色分配给 table 值

Assigning colors to table values using Choroplethr

我正在尝试使用 choroplethr 制作县级地图。目前,我的 csv 中的列值下有 3 个分类整数(1、2、3),它们因每个县而异。 region 列包含县 fips。

我想将以下值显示为相应的标签,颜色(值=标签=颜色):

0 = "None" = "white", 1 = "MD" = "#64acbe", 2 = "DO" = "#c85a5a", 3 = "Both" = "#574249",

我尝试了几种 scale_fill_brewer 的组合,但没有得到我想要的结果。任何帮助都会很棒。这是模拟我正在使用的数据的代码:

library(choroplethr)
library(ggplot2)
library(choroplethrMaps)

Res <- data.frame(

region = c(45001, 22001, 51001, 16001, 19001, 21001, 29001, 40001, 8001, 19003, 16003, 17001, 18001, 28001, 38001, 31001, 39001, 42001, 53001, 55001, 50001, 72001, 72003, 72005, 72007, 72009, 45003, 27001),

value = c(0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3), 
stringsAsFactors = FALSE)

county_choropleth(Res, 
            title = "All United States Medical Residencies",
            legend = "Types of Medical Residencies"
             )

感谢您使用 Choroplethr。

我认为这里有几个问题。我要解决的第一个问题是您的 value 列包含数字数据。这本身不是问题。但是因为您实际上是在使用它来编码分类数据(即 "MD"、"OD" 等),所以这是一个问题。因此,我的首要任务是将数据类型从数字数据更改为字符数据:

> class(Res$value)
[1] "numeric"
> Res$value = as.character(Res$value)
> class(Res$value)
[1] "character"

现在我将 "numbers" 替换为您想要的类别名称:

> Res[Res=="0"] = "None"
> Res[Res=="1"] = "MD"
> Res[Res=="2"] = "DO"
> Res[Res=="3"] = "Both"
> head(Res)
  region value
1  45001  None
2  22001    MD
3  51001    DO
4  16001  Both
5  19001  None
6  21001    MD

现在开始第二期。您说您正在尝试使用 scale_fill_brewer。该功能用于使用 Brewer 秤。但你不想要这里的那些。你说你有自己的秤。所以你想使用 scale_fill_manual

county_choropleth(Res) + 
  scale_fill_manual(values=c("None" = "#ffffffff",  
                             "MD" = "#64acbe", 
                             "DO" = "#c85a5a", 
                             "Both" = "#574249"),
                    name="Types of Medical Residencies")

注:choroplethr所谓的"legend"(其实就是图例的name)其实是ggplot2刻度的属性。特别是,它是规模的name。因此,如果您使用自己的秤,则不能再使用 choroplethr 的 legend 参数。

当然,现在我们有一个新问题:阿拉斯加和夏威夷都是黑色的。我实际上忘记了这个问题(自从我在 Choroplethr 上工作以来已经有一段时间了)。发生这种情况的原因是非常技术性的,也许比您关心的更详细,但为了完整起见,我会在这里提及它:choroplethr 使用 ggplot2 注释在适当的位置渲染 AK 和 HI。 choropelthr + ggplot_scale 范式在这里不适用于 AK 和 HI,因为 ggplot 不会向注释传播额外的层/比例。为了解决这个问题,我们必须使用 choroplethr 的面向对象特性:

c = CountyChoropleth$new(Res)
c$title = "All United States Medical Residencies"
c$ggplot_scale = scale_fill_manual(values=c("None" = "#ffffffff", "MD" = "#64acbe", "DO" = "#c85a5a", "Both" = "#574249"), 
                                   name="Types of Medical Residencies")
c$render()