0

我有一个数据框:

| Country       | Country_code | Id   | Unique_person |
|---------------|--------------|------|---------------|
| India         | IN           | 40   | 2             |
| China         | CN           | 3781 | 1             |
| Mexico        | MX           | 40   | 1             |
| United States | US           | 1000 | 14            |
| United States | US           | 3781 | 566           |
| United States | US           | 40   | 43            |
| United States | US           | 65   | 908           |
| United States | US           | 815  | 78            |

我需要使用 ggplot2 绘制世界地图,以便“unique_person”的大小根据每个国家/地区不同的颜色编码“Id”而变化。由于我没有纬度和经度,我无法绘制世界地图。有人可以帮我解决这个问题吗?

4

2 回答 2

0

虽然我可能无法正确理解 Id 问题,但您可以在不使用纬度和经度的情况下绘制地图,如下所示。我希望这可以帮助你。

library(rworldmap)
dat<-data.frame("country"=c("India", "China", "Mexico", "United States"), "Unique_person"=c(2, 1, 1, 14))
sdat <- joinCountryData2Map(dat, joinCode="NAME", nameJoinColumn="country")
mapCountryData(sdat, nameColumnToPlot="Unique_person", catMethod="fixedWidth", addLegend = TRUE)

图片

于 2020-04-28T02:27:36.577 回答
0

有多种绘制地理数据的方法,一个好的和简单的开始是ggplot2结合maps提供地理多边形映射世界国家的包使用。

您可以使用world地图数据集并将其与您的数据合并,例如基于国家名称,以获得地理坐标。我还没有完全理解您想要绘制的内容,但您的基本情况可能是:

数据

structure(list(Country = c("India", "China", "Mexico", "United States", 
"United States", "United States", "United States", "United States"
), Country_code = c("IN", "CN", "MX", "US", "US", "US", "US", 
"US"), Id = c(40, 3781, 40, 1000, 3781, 40, 65, 815), Unique_person = c(2, 
1, 1, 14, 566, 43, 908, 78)), class = c("spec_tbl_df", "tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -8L), spec = structure(list(
    cols = list(Country = structure(list(), class = c("collector_character", 
    "collector")), Country_code = structure(list(), class = c("collector_character", 
    "collector")), Id = structure(list(), class = c("collector_double", 
    "collector")), Unique_person = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
    "collector")), skip = 1), class = "col_spec"))

代码

library(ggplot2)
library(maps)

data$Country[data$Country == 'United States'] <- "USA" # names are different for USA in datasets

data <- merge(data, 
              map_data("world"), by.x = "Country", by.y = "region") %>%
  arrange(Country, order)

ggplot() + 
  # world map
  geom_polygon(data = map_data("world"), 
               aes(x=long, y = lat, group = group),
               fill = "grey50") +
  # custom map
  geom_polygon(data = data,
               aes(x=long, y = lat, group = group, fill = Id))

于 2020-04-28T08:35:51.493 回答