R语言 在世界Map上为特定国家/地区着色并添加Map点城市

rpppsulh  于 2023-02-01  发布在  其他
关注(0)|答案(1)|浏览(257)

我想设计一张世界Map来显示我的调查参与者来自哪个国家和哪个城市。我使用了highcharter软件包。
第一部分是:给这些国家涂上颜色--〉效果很好!2一个从0到1的量表被创建。3第二部分是:添加城市--〉点被创建,但是蓝色的国家消失了!比例改变了,现在是从城市中诱导出来的。
我尝试更改代码的顺序,但没有任何效果。

library(dplyr)
library(maps)
library(magrittr)
# I use the dataset called iso3166 from the {maps} package and rename it date

dat <- iso3166
head(dat)

# I rename the variable a3 by iso-a3

dat <- rename(dat, "iso-a3" = a3)
head(dat)

# I create a vector with the countries I want to colour 

part1X_countries <- c("CHE", "FRA", "USA", "GBR", "CAN", "BRA")

dat$part1X <- ifelse(dat$`iso-a3` %in% part1X_countries, 1, 0)
head(dat)

# I add the name of cities with geographical coordinates

cities <- data.frame(
  name = c("St Gallen", "Fort Lauderdale", "Paris", "Nottingham", "Winnipeg", "Chicago", "Leeds", "Montréal", "New Rochelle", "São Paulo", "Saint-Genis-Pouilly", "Canterbury"),
  lat = c(47.42391, 26.122438, 48.866667, 52.950001, 49.8955, 41.881832, 53.801277, 45.5016889, 40.9232, -23.5489, 46.24356, 51.279999),
  lon = c(9.37477, -80.137314, 2.333333, -1.150000, -97.1383, -87.623177, -1.548567, -73.567256, -73.7793, -46.6388, 6.02119, 1.080000))

# I create my worldmap with countries and cities

worldmap <- hcmap(
  map = "custom/world-highres3", # high resolution world map
  data = dat, # name of dataset
  value = "part1X",
  joinBy = "iso-a3",
  showInLegend = FALSE, # hide legend
  download_map_data = TRUE
) %>%
  hc_add_series(
  data = cities, 
  type = "mappoint",
  name = "Cities"
) %>%
  hc_title(text = "Representation of participants by country")```
ycl3bljg

ycl3bljg1#

您需要为hcmap定义一个颜色键并添加一个颜色轴。下面的代码保留了来自国家的颜色,并将国家的名称作为黑色Map点添加到顶部。

worldmap <- hcmap(
  map = "custom/world-highres3", # high resolution world map
  data = dat, # name of dataset
  value = "part1X",
  joinBy = "iso-a3",
  colorKey = "value",
  showInLegend = F, # hide legend
  download_map_data = TRUE)  %>% 
  hc_colorAxis(min = min(dat$part1X), 
               max = max(dat$part1X)) %>% 
  hc_add_series(
    data = cities, 
    type = "mappoint",
    name = "Cities",
    dataLabels = list(enabled = TRUE, format = '{point.name}'),
    latField = "lat",
    longField = "lon",
    # color = "color"
    valueField = "part1X"
  ) %>%
  hc_title(text = "Representation of participants by country")
worldmap

相关问题