将条形图绘制到 R ggplot2 中的地图
Plotting bar charts to a map in R ggplot2
我想在 ggplot2 中向地图添加条形图。存在类似的问题 (this one and this one),但他们的答案涉及 ggsubplot,已弃用。
geom_scatterpie()
提供了一种使用饼图执行此操作的方法 (example 1 but also see example 2), but pie charts are not as visually intuitive as bar charts. Similarly, we can plot bubble size onto a map using geom_sf(size=)
as explained here。那么有没有一种方法可以使用条形图来执行此操作?
每个位置制作一个条的可重现示例:
# devtools::install_github("hrbrmstr/albersusa")
library(albersusa)
library(sf)
library(ggplot2)
# make a map
statesus <- fortify(usa_sf("laea"))
p <- ggplot() +
geom_sf(data=statesus, size=0.4)
# set up the data
lat <- c(-68.24, -109.88, -80.88, -113.85)
lon <- c(44.35, 38.24, 25.37, 48.75)
park <- c("Acadia", "Canyonlands", "Everglades", "Glacier")
proportion <- c(0.10, 0.80, 0.05, 0.45) # bar heights
parkdat <- data.frame(lat=lat, lon=lon, park=park, proportion=proportion)
parkdatsf <- st_as_sf(parkdat,
coords=c(lon="lon", lat="lat"),
crs=4326,
agr="constant")
# add points to the map (ideally these would be bars)
p + geom_sf(data=parksdatsf)
添加条形作为点对我来说有点尴尬。如果您想在地图上添加条形图,一种选择是使用 geom_rect
,如下所示:
library(sf)
library(ggplot2)
library(albersusa)
p <- ggplot() +
geom_sf(data=usa_sf(), size=0.4) +
theme_minimal()
scale <- 10
width <- 4
p +
geom_rect(data=parkdat, aes(xmin = lat - width / 2, xmax = lat + width / 2, ymin = lon, ymax = lon + proportion * scale, fill = park))
我想在 ggplot2 中向地图添加条形图。存在类似的问题 (this one and this one),但他们的答案涉及 ggsubplot,已弃用。
geom_scatterpie()
提供了一种使用饼图执行此操作的方法 (example 1 but also see example 2), but pie charts are not as visually intuitive as bar charts. Similarly, we can plot bubble size onto a map using geom_sf(size=)
as explained here。那么有没有一种方法可以使用条形图来执行此操作?
每个位置制作一个条的可重现示例:
# devtools::install_github("hrbrmstr/albersusa")
library(albersusa)
library(sf)
library(ggplot2)
# make a map
statesus <- fortify(usa_sf("laea"))
p <- ggplot() +
geom_sf(data=statesus, size=0.4)
# set up the data
lat <- c(-68.24, -109.88, -80.88, -113.85)
lon <- c(44.35, 38.24, 25.37, 48.75)
park <- c("Acadia", "Canyonlands", "Everglades", "Glacier")
proportion <- c(0.10, 0.80, 0.05, 0.45) # bar heights
parkdat <- data.frame(lat=lat, lon=lon, park=park, proportion=proportion)
parkdatsf <- st_as_sf(parkdat,
coords=c(lon="lon", lat="lat"),
crs=4326,
agr="constant")
# add points to the map (ideally these would be bars)
p + geom_sf(data=parksdatsf)
添加条形作为点对我来说有点尴尬。如果您想在地图上添加条形图,一种选择是使用 geom_rect
,如下所示:
library(sf)
library(ggplot2)
library(albersusa)
p <- ggplot() +
geom_sf(data=usa_sf(), size=0.4) +
theme_minimal()
scale <- 10
width <- 4
p +
geom_rect(data=parkdat, aes(xmin = lat - width / 2, xmax = lat + width / 2, ymin = lon, ymax = lon + proportion * scale, fill = park))