【问题标题】:How to Remove State Abbreviations from a Choroplethr Map如何从 Choroplethr 地图中删除州缩写
【发布时间】:2020-07-17 04:34:27
【问题描述】:

我正在使用如下图所示的choroplethr 地图。如何简单地删除州缩写?

这里是复制代码:

library(choroplethr)
library(choroplethrMaps)

data(df_pop_state)
df_pop_state$value <- as.numeric(df_pop_state$value)

state_choropleth(df_pop_state, num_colors = 1,
                             title = "2012 State Population Estimates",
                             legend = "Population")

【问题讨论】:

    标签: r ggplot2 maps choroplethr


    【解决方案1】:

    此函数返回一个 ggplot 对象,因此您可以手动检查图层并删除不需要的图层(此处您要删除 GeomText 图层):

    states <- state_choropleth(
      df_pop_state, 
      num_colors = 1,
      title = "2012 State Population Estimates",
      legend = "Population"
    ) 
    
    layer_no <- grep("GeomText", sapply(states$layers, function(x) class(x$geom)[1]))
    
    states$layers[[layer_no]] <- NULL
    
    states
    

    【讨论】:

      【解决方案2】:

      感谢您使用 choroplethr。请注意,Choroplethr 使用 R6 对象。事实上,state_choropleth 函数只是StateChoropleth R6 对象的一个​​便捷包装器:

      > state_choropleth
      function (df, title = "", legend = "", num_colors = 7, zoom = NULL, 
          reference_map = FALSE) 
      {
          c = StateChoropleth$new(df)
          c$title = title
          c$legend = legend
          c$set_num_colors(num_colors)
          c$set_zoom(zoom)
          if (reference_map) {
              if (is.null(zoom)) {
                  stop("Reference maps do not currently work with maps that have insets, such as maps of the 50 US States.")
              }
              c$render_with_reference_map()
          }
          else {
              c$render()
          }
      }
      <bytecode: 0x7fdda6aa3a10>
      <environment: namespace:choroplethr>
      

      如果您查看source code,您会看到对象上有一个字段可以执行您想要的操作:show_labels。默认为TRUE

      我们可以通过简单地使用StateChoropleth 对象(不是函数)创建地图并将show_labels 设置为FALSE 来获得您想要的结果。

      c = StateChoropleth$new(df_pop_state)
      c$title = "2012 State Population Estimates"
      c$legend = "Population"
      c$set_num_colors(1)
      c$show_labels = FALSE
      c$render()
      

      我之所以选择这种方法,是因为总的来说,我发现 R 中的许多函数都有大量参数,这可能会造成混淆。缺点是函数比对象更容易记录(尤其是在 R 中),所以经常出现这样的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多