【问题标题】:Discrete values in US map legend using plot_usmap美国地图图例中的离散值使用 plot_usmap
【发布时间】:2020-04-20 19:21:56
【问题描述】:

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

我的代码是:

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

输出图是:

【问题讨论】:

    标签: r legend usmap


    【解决方案1】:

    您必须将处理转换为factor 或character。然后可以通过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 package (v0.3.0) 于 2020-04-20 创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-08
      • 2016-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多