以下是一个示例代码,使用ggplot2和maps包绘制世界地图,并在地图上标出随机的10个国家。根据标注点的数量,我们使用scale_fill_gradient函数将国家着色。

library(ggplot2)
library(maps)

# 生成一个包含随机国家名称和点数量的数据框
set.seed(123)
n_countries <- 10
countries <- sample(maps::map('world', plot = FALSE)$names, n_countries)
n_points <- sample(1:100, n_countries, replace = TRUE)
data <- data.frame(country = countries, n_points = n_points)

# 绘制地图
world_map <- ggplot() +
  geom_map(map = maps::map('world', plot = FALSE), aes(map_id = region), fill = 'white', color = 'black') +
  expand_limits(x = maps::map('world', plot = FALSE)$xlim, y = maps::map('world', plot = FALSE)$ylim) +
  coord_map()

# 在地图上标注点
country_points <- world_map +
  geom_point(data = data, aes(x = lon, y = lat, size = n_points), color = 'red') +
  scale_size_continuous(range = c(1, 10))

# 根据点数量着色
colored_countries <- country_points +
  geom_map(map = maps::map('world', plot = FALSE), aes(map_id = region, fill = n_points), color = 'black') +
  scale_fill_gradient(low = 'white', high = 'blue')

colored_countries

运行代码后会得到一个带有10个随机点的地图,点的大小表示点的数量,颜色根据点的数量从白色到蓝色渐变。可以根据需要更改点的数量和颜色。


原文地址: https://www.cveoy.top/t/topic/oiW6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录