【问题标题】:Customize colors in ggplot2's geom_polygon using brewer palette使用 brewer 调色板自定义 ggplot2 的 geom_polygon 中的颜色
【发布时间】:2018-04-03 09:59:53
【问题描述】:

我想复制使用此链接中的确切代码构建的地图 - 仅来自“第 1 步,构建初始地图”:

https://www.r-bloggers.com/user-question-how-to-add-a-state-border-to-a-zip-code-map/

但是,我希望颜色不是蓝色,而是其他颜色。所以,我只在代码中添加了一行 - 就在 ggplot_polygon 之后:

+scale_fill_brewer(palette = 'OrRd') 

但它不起作用。知道为什么吗?

下面是我的代码:

library(choroplethr)
library(ggplot2)
library(devtools)
install_github('arilamstein/choroplethrZip@v1.3.0')
library(choroplethrZip)

# load the data 
data(df_zip_demographics)
str(df_zip_demographics)
df_zip_demographics$value = df_zip_demographics$percent_white

# create the map
zip_map = ZipChoropleth$new(df_zip_demographics)
zip_map$ggplot_polygon = geom_polygon(aes(fill = value), 
                                      color = NA) +
  scale_fill_brewer(palette = 'OrRd')
zip_map$set_zoom_zip(state_zoom  = c("new york", "new jersey"), 
                     county_zoom = NULL, 
                     msa_zoom    = NULL, 
                     zip_zoom    = NULL) 
zip_map$title = "New York and New Jersey ZCTAs"
zip_map$legend = "Percent White"
zip_map$set_num_colors(4)
choro = zip_map$render()
choro

【问题讨论】:

    标签: r ggplot2 color-palette choroplethr


    【解决方案1】:

    通过检查代码,choro 是被渲染的 ggplot2 对象,因此这是添加更多 ggplot2 元素的地方,而不是 zip_map$ggplot_polygon,它只接受 geom_polygon 赋值。

    # create the map
    zip_map = ZipChoropleth$new(df_zip_demographics)
    zip_map$ggplot_polygon = geom_polygon(aes(fill = value), 
                                      color = NA)
    zip_map$set_zoom_zip(state_zoom  = c("new york", "new jersey"), 
                     county_zoom = NULL, 
                     msa_zoom    = NULL, 
                     zip_zoom    = NULL) 
    zip_map$title = "New York and New Jersey ZCTAs"
    zip_map$legend = "Percent White"
    zip_map$set_num_colors(4)
    choro = zip_map$render()
    choro
    
    # Change fill to brewer palette
    choro + scale_fill_brewer(palette = 'OrRd')
    

    【讨论】:

    • 非常感谢!谁能想到这么简单!
    猜你喜欢
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    相关资源
    最近更新 更多