"Corrupted" 世界地图的颜色填充 - 使用 geom_map
"Corrupted" color fill of the world map - using geom_map
我想使用 ggplot、maps 和 mapdata 在世界地图上可视化一些数据
.xls 文件的 link 是 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 存储库?
您是否尝试过 left_join
而不是合并?
没有 mapka 数据就无法调试您的代码。
最好给我们一些可以复制您遇到的问题的代码。我能够在不使用您提供的 link 的情况下复制您的代码。我的建议是使用 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)
)
我想使用 ggplot、maps 和 mapdata 在世界地图上可视化一些数据
.xls 文件的 link 是 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 存储库?
您是否尝试过 left_join
而不是合并?
没有 mapka 数据就无法调试您的代码。
最好给我们一些可以复制您遇到的问题的代码。我能够在不使用您提供的 link 的情况下复制您的代码。我的建议是使用 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)
)