2

我正在使用 usmap::plot_usmap() 绘制一组“治疗”县,这样对于已识别的县,治疗 = 1,否则为 0。我希望图例反映变量是离散的(0/1)而不是显示连续的颜色比例的事实?我的数据集有 2 个变量:fips 和治疗。

我的代码是:

library(usmap)
library(ggplot2)

  plot_usmap(regions = "county", data=data, values = "treatment",color="grey")+ 
  theme(panel.background = element_rect(colour = "black"))+
  scale_fill_gradient(low = "white", high = "blue",name = "treatment",
                      breaks=c(0,1), limits = c(0, 1)) + 
  theme(legend.position = "right") 

输出图是: 在此处输入图像描述

4

1 回答 1

3

您必须将治疗转换为factorcharacter。然后可以通过 设置颜色scale_fill_manual。使用一些随机示例data试试这个:

library(usmap)
library(ggplot2)
library(dplyr)

# example data
set.seed(42)
data <- utils::read.csv(system.file("extdata", "county_fips.csv", 
                                  package = "usmap")) %>% 
  select(fips) %>% 
  mutate(treatment = sample(c(0, 1), nrow(.), replace = TRUE))

# Convert treatment to factor
data <- mutate(data, treatment = factor(treatment))

plot_usmap(regions = "county", data=data, values = "treatment",color="grey")+ 
  theme(panel.background = element_rect(colour = "black")) +
  scale_fill_manual(values = c(`0` = "white", `1` = "blue"), name = "treatment") + 
  theme(legend.position = "right")

reprex 包于 2020-04-20 创建(v0.3.0)

于 2020-04-20T20:06:58.423 回答