【问题标题】:"Corrupted" color fill of the world map - using geom_map [duplicate]世界地图的“损坏”颜色填充 - 使用 geom_map [重复]
【发布时间】:2019-06-06 22:16:09
【问题描述】:

我想使用 ggplot、maps 和 mapdata 在世界地图上可视化一些数据

.xls 文件的链接是here*

让我们看看代码:

library(maps)
library(mapdata)
library(readxl)
library(ggplot2)
library(ggthemes)
library(mapproj)

mapka <- read_xls(path="Yourpath/mapy2.xls")

m <-map_data("world")
choro <-merge(m, mapka, by="region", all.x=TRUE)
for (i in 1:nrow(choro)) {
  if (is.na(choro$a[i]==TRUE)){choro$a[i]<-0}
  if (is.na(choro$b[i]==TRUE)){choro$b[i]<-0}}

ggplot()+
  geom_map(data=choro, map=choro, aes(long,lat, map_id=region, fill=a)) +
  theme_bw() +
  xlab("") +
  ylab("") + 
  scale_x_continuous(labels=NULL) +
  scale_y_continuous(labels=NULL)

但是,当我执行代码时,我得到了这个奇怪的图像:

怎么了?以前我没有这样的问题。看起来很可怕。

*有人知道更好的免费 .xls/.xlsx 存储库吗?

【问题讨论】:

    标签: r ggplot2 colors spatial


    【解决方案1】:

    最好给我们一些代码来复制您遇到的问题。我能够在不使用您提供的链接的情况下复制您的代码。我的建议是使用 left_join() 而不是 merge()replace_na() 而不是 for 循环。

    library(maps)
    library(tidyverse)
    library(mapdata)
    library(ggthemes)
    library(mapproj)
    
    m <- 
      map_data("world") 
    
    mapka <-
      m %>% 
      distinct(region) %>% 
      slice(1:100) %>% 
      mutate(a = c(1:100)*40)
    
    # replicates your issue
    choro <- merge(m, mapka, by = "region", all.x = TRUE)
    
    for (i in 1:nrow(choro)) {
      if (is.na(choro$a[i]) == TRUE) {
        choro$a[i] <- 0
      }
    }  
    
    ggplot() +
      geom_map(
        data = choro, map = choro, 
        aes(long, lat, map_id = region, fill = a)
      )
    
    # using left_join and replace_na
    choro <-
      m %>% 
      left_join(mapka) %>% 
      mutate(a = replace_na(a, 0))
    
    ggplot() +
      geom_map(
        data = choro, map = choro, 
        aes(long, lat, map_id = region, fill = a)
      )
    

    【讨论】:

    • 感谢您的复杂建议,我承认我需要学习优化我的 R 代码。让我问额外的问题。如何为 a=0(灰色)和 a>0 蓝色调色板设置颜色 brewer?
    • 您可以跳过na_replace() 步骤,NA 的值默认为灰色。对于颜色 brewer,您可以使用此代码 + scale_fill_distiller(palette = "Blues", direction = 1, na.value = "grey70")。如您所见,您可以在此处调整NA 值的颜色。有关优化代码的更多信息,我会推荐 Hadley Wickham 的 R for Data Science 一书(也可在线免费)。
    【解决方案2】:

    您是否尝试过left_join 而不是合并? 如果没有 mapka 数据,就无法调试您的代码。

    【讨论】:

      猜你喜欢
      • 2019-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-25
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      相关资源
      最近更新 更多