图例未显示在用R创建的地图中

时间:2018-12-12 02:54:27

标签: r plot legend

我使用以下代码创建了地图,但图例未显示。我试图改变页边距和图例坐标,但仍然没有显示。有人可以帮忙吗?示例数据在Github上,链接在这里:dataset。理想情况下,我想要一个带有legend的图像,但是我正在生成一个没有legend的图像。我使用了类似的代码来生成两个图像。

library(rgdal); library(dplyr);library(readr);
library(maptools); library(plotrix); 
library(raster);library(sp)
library(raster);library(sp)
library(grDevices);library(mapproj);
library(lubridate); library(grid)
library(gridExtra);library(spdep); library(rgeos)



shape0<- shapefile("Ethiopia/admin_levels/gadm36_ETH_0")
shape1<- shapefile("Ethiopia/admin_levels/gadm36_ETH_1")
shape2<- shapefile("Ethiopia/admin_levels/gadm36_ETH_2")


png(paste0("Ethiopia/figures/NGA_HT_Estimates_",
           format(today(), '%Y%m%d'),
           ".png"),
    height = 6 * 1.15, width = 6 * 1.15, res = 400, unit = "in")
par(mar = c(5,0,7,0))
plotvar = dat$BMI
brks = seq(0, 0.8, length = 11)
nclr <- length(brks) - 1

plotclr <- rev(brewer.pal(nclr, "RdYlBu"))
colornum <- findInterval(plotvar, brks, all.inside = T)
colcode <- plotclr[colornum]

plot(shape2, border = "black", lwd = 0.5, col = colcode)
plot(shape1, border = "black", lwd = 2, add = T)
plot(shape0, border = "black", lwd = 3, add = T)

color.legend(4.5, 1, 6, 3.5, rect.col = plotclr, gradient="y",
             legend = paste0(seq(0, 0.8, length = 4) * 100, "%"),
             align = "rb", cex = 1.4)

title(main = list("Prevalence of Overweight (<=25kg/m2) among\n Women 18 years and Older in Ethiopian Zones", 
       sub =  "Raw Estimates", cex.main = 1.4,   font.main= 4, col.main= "black", 
  cex.sub = 0.75, font.sub = 3, col.sub = "black")

dev.off()

1 个答案:

答案 0 :(得分:1)

图例不显示的常见原因是绘图被裁剪到绘图区域。可以通过par(xpd = TRUE)进行更改,该功能允许您将图例放置在绘图区域之外。