我是R的初学者,我正在尝试制作一张世界地图,该地图将根据特定国家/地区的人均GDP为其着色,该国家/地区的人均GDP存储在另一个数据框中。这是我的代码(可在网上找到):
install.packages(c("cowplot", "googleway", "ggplot2", "ggrepel", "ggspatial", "libwgeom", "sf", "rnaturalearth", "rnaturalearthdata", "rgeos"))
library("ggplot2")
theme_set(theme_bw())
library("sf")
library("rnaturalearth")
library("rnaturalearthdata")
library("rgeos")
world <- ne_countries(scale = "medium", returnclass = "sf")
ggplot(data = world) +
geom_sf() +
xlab("Longitude") + ylab("Latitude") +
ggtitle("World map", subtitle = paste0("(", length(unique(world$name)), " countries)"))
这带来了241个国家/地区的地图。但是,我的GDP数据框仅存储182个国家/地区的信息。因此,当尝试使用FILL =时,我收到一个错误:
ggplot(data = world) +
geom_sf(aes(fill = GDP.data$`US$`)) +
scale_fill_viridis_c(option = "plasma", trans = "sqrt")
Error: Aesthetics must be either length 1 or the same as the data (241): fill
我该如何克服这个问题,并仍然使我在数据框中具有的国家/地区成为彩色?
非常感谢您!
答案 0 :(得分:0)
这是一个有效的示例,遵循@stefan的有关将数据连接到地图数据框的建议。
在此示例中,我创建了一个有限的数据框,其中包含选定国家/地区的gdp信息my_gdp
:
gdp_data <- data.frame(
name = c("Australia", "China", "Brazil"),
my_gdp = c(1.43, 13.61, 1.86)
)
name my_gdp
1 Australia 1.43
2 China 13.61
3 Brazil 1.86
您可以merge
(或使用dplyr::left_join
)将my_gdp
添加到您的world
数据框中。使用all.x
将确保所有国家/地区仍可用于绘图,并在没有gdp值的地方填写NA
。
plot_data <- merge(world, gdp_data, by = "name", all.x = TRUE)
然后,仅使用该最终数据框plot_data
来创建绘图。与在ggplot
中引用两个不同的数据帧相比,这将更易于管理,并确保您具有相同数量的数据行以用于绘制国家/地区和填写gdp。
ggplot(data = plot_data) +
geom_sf(aes(fill = my_gdp)) +
scale_fill_viridis_c(option = "plasma", trans = "sqrt") +
ggtitle("World map (GDP in trillions $)", subtitle = paste0("(", length(unique(world$name)), " countries)"))
图解