2

I created a map with the code below and my legend is not showing up. I have tried to vary the margins and the legend coordinates but it still does not show up. Can anyone help? Sample data is on Github linked here: dataset. Ideally, I would like an image with a legend but I am generating one without a legend. I used similar codes to generate both images.

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()
ify
  • 33
  • 4

1 Answers1

1

A common reason why the legend doesn't show is that the plotting is clipped to the plot region. This can be changed by par(xpd = TRUE), which allows you to place the legend outside of the plot region.

Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
  • I tried this and it didn't work. I included some sample data to reproduce the problem – ify Dec 12 '18 at 14:31
  • I'm having trouble finding the function `shapefile`; is it part of the package `shapefiles`? If not which package does it belong to? – Chris Ruehlemann Dec 12 '18 at 17:01
  • I believe it is part of rgdal but you can download the other packages just in case. Thanks for the help. – ify Dec 13 '18 at 00:59