我使用 ggplot 比使用 base R plot 多,所以我不知道如何用 base R 添加图例。此外,我不熟悉 rnaturalearth 包和数据,所以我所做的只是复制你的情节使用 ggplot 并添加一个图例。我不确定这是否是您想要的图例,但我所做的只是用 ggplot 制作完全相同的图并添加了图例。如果它不是您想要的,您可以自定义图例。
library(ggplot2)
ggplot(data = world) +
geom_sf(aes(fill = 1:nrow(world))) +
scale_fill_viridis_c(name = "", alpha = 0.5, option = "plasma", trans = "sqrt") +
theme_classic()
对于多个变量的并排图,我们可以使用gridExtra 包。
library(gridExtra)
plot1 <- ggplot(data = world) +
geom_sf(aes(fill = 1:nrow(world))) +
scale_fill_viridis_c(name = "", alpha = 1, option = "plasma", trans = "sqrt") +
ggtitle("adm0_dif")+
theme(plot.title = element_text(hjust = 0.5),
panel.background = element_rect(fill = "white", colour = "white"))
plot2 <- ggplot(data = world) +
geom_sf(aes(fill = labelrank)) +
scale_fill_viridis_c(name = "", alpha = 1, option = "plasma", trans = "sqrt") +
ggtitle("labelrank") +
theme(plot.title = element_text(hjust = 0.5),
panel.background = element_rect(fill = "white", colour = "white"))
grid.arrange(plot1, plot2, ncol=2)
对于未按数字编码的变量,如featurecla,请改用scale_fill_manual
plot_fea <- ggplot(data = world) +
geom_sf(aes(fill = featurecla), show.legend = F) +
scale_fill_manual(name = "", values = c("mediumaquamarine"))+
ggtitle("featurecla") +
theme(plot.title = element_text(hjust = 0.5),
panel.background = element_rect(fill = "white", colour = "white"))
plot_fea
注意我只为scale_fill_manual 中的值提供了值(“mediumaquamarine”),因为它只包含一个唯一变量。传递给 value 的颜色数量必须与列中唯一变量的数量相匹配。