简体   繁体   English

美国 map 图例中的离散值使用 plot_usmap

[英]Discrete values in US map legend using plot_usmap

I am plotting a group of "treatment" counties, using usmap::plot_usmap(), such that treatment=1 for the identified counties an 0 otherwise.我正在使用 usmap::plot_usmap() 绘制一组“治疗”县,这样对于已识别的县,治疗 = 1,否则为 0。 I would like the legend to reflect the fact that the variable is discrete (0/1) rather than show a continuous scale of colors?我希望图例反映变量是离散的(0/1)而不是显示 colors 的连续比例这一事实? My dataset has 2 variables: fips and treatment.我的数据集有 2 个变量:fips 和治疗。

My code is:我的代码是:

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") 

The output graph is: output 图为: 在此处输入图像描述

You have to convert treatment to a factor or character .您必须将处理转换为factorcharacter Colors can then be set via scale_fill_manual .然后可以通过 scale_fill_manual 设置scale_fill_manual Using some random example data try this:使用一些随机示例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")

Created on 2020-04-20 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2020 年 4 月 20 日创建

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

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