ggplot2 案例:使用 ggplot2 绘制绘制一幅气泡地图展示各国疫情状况

2020-07-06 17:57:39 浏览数 (1)

新冠肺炎确诊患者们都分布在那里呢?约翰·霍普金斯大学提供了一份数据集,使用这份数据集我们可以绘制一幅气泡地图展示这些确诊患者的分布,代码比较简单:

首先导入我们需要的几个 R 包:

代码语言:javascript复制
library(ggplot2)
library(sf)
library(readr)
library(dplyr)

导入世界地图并把 crs 转换成 4326(其实这份数据的 crs 就是 4326):

代码语言:javascript复制
worldmap <- read_sf('world.geo.json') %>%
  st_transform(crs = 4326)

把疫情数据读取进来并根据经纬度坐标把这个数据框转换成 sf 对象,同样使用 4326 投影坐标系,这样地图和数据才不会分家:

代码语言:javascript复制
read_csv('time_series_19-covid-Confirmed.csv') %>%
  select(Lat, Long, `3/4/20`) %>%
  `colnames<-`(c("lat", "long", "con")) %>%
  st_as_sf(coords = c("long", "lat"), crs = 4326) -> con_df

最后绘制地图:

代码语言:javascript复制
mybreaks <- c(1, 20, 100, 1000, 50000)
ggplot(worldmap)  
  geom_sf(size = 0.1, color = "white", fill = NA)  
  geom_sf(data = con_df, aes(size = con,
                             color = con))  
  theme_modern_rc(base_family = cnfont,
                  subtitle_family = cnfont,
                  caption_family = cnfont,
                  grid = "")  
  worldtilegrid::theme_enhance_wtg()  
  theme(panel.grid = element_blank())  
  scale_size_continuous(name = "Confirmed cases",
                        trans = "log",
                        range = c(1, 7),
                        breaks = mybreaks,
                        labels = c("1-19", "20-99", "100-999", "1,000-49,999", "50,000 "))  
  scale_color_viridis_c(option = "inferno",
                        name = "Confirmed cases",
                        trans = "log",
                        breaks = mybreaks,
                        labels = c("1-19", "20-99", "100-999", "1,000-49,999", "50,000 "))  
  guides(color = guide_legend())  
  labs(title = "新冠肺炎的全球分布",
       subtitle = "截止:2020 年 3 月 4 日",
       caption = "数据来源: CSSEGISandData/COVID-19: Novel Coronavirus (COVID-19) Cases, provided by JHU CSSEnhttps://github.com/CSSEGISandData/COVID-19n绘制:TidyFriday")

❝本文的附件和代码可以从知识星球下载:https://t.zsxq.com/iEYVjqr ❞

0 人点赞