简体   繁体   中英

R: tmap Legend Formatting

I am trying to create a function to map different variables for a specific state's school districts. However I a running into some problems formatting the legend. At the moment I have it laid out the best way to fit the maps(horizontally), but some of the text is being cut off (Below Average Poverty Rate), and I'd like to add % to the number labels in the legend. My code and an image of the legend is below. Any help you can provide would be very much appreciated. Thank You.

MakeLEAMap <-function(StateNum,NCHE_VAR,VAR1_NAME,In,Folder){
  as.character(substitute(StateNum))
  as.character(substitute(NCHE_VAR))
  as.character(substitute(NCHE_In))
  as.character(substitute(VAR1_NAME))
  as.character(substitute(Folder))

  map <- 
    tm_shape(LEA_1415_New[LEA_1415_New@data$STATEFP == StateNum, ]) +
    tm_polygons(NCHE_VAR,border.col="#000000", lwd= .5, textNA="Below Average \nPoverty Rate" ,  palette = 'Blues', style="quantile", 
                title=paste(In," State LEA Map: ",VAR1_NAME),
                legend.is.portrait = FALSE) +
    tm_text("LCITY", size=NCHE_VAR,scale=.8, root=2,print.tiny = FALSE, size.lowerbound = .85, bg.alpha = .75, 
            remove.overlap = TRUE,legend.size.show = FALSE, col="black") +
    tm_layout( legend.title.size = 3,
              frame = FALSE, inner.margins = c(0,.0,.05,.0), asp = 1.5,
              legend.text.size = 1, 
              legend.outside=TRUE, legend.outside.position = 'bottom',
              legend.frame = TRUE,
              legend.outside.size = .3, legend.position = c(-0.1, 0.3))

  save_tmap(map, filename=paste("State_Maps_TEST/",Folder,"/",In,".pdf", sep = ''),width=8, height=8 ) 
}
MakeLEAMap("48","Abv_Diff_Home_Pov","% Children in Poverty  minus \n% Children HCY (Ages5-17)", 
           "TX","ALL")

Here is what the legend looks like now

To make the legend show percentages use this function inside your tm_polygons call:

legend.format=list(fun=function(x) paste0(formatC(x, digits=0, format="f"), " %"))

You can play with the digits (decimal points) and you can drop the space before % sign if you desire.

To make the legend more legible increase the space around your map by making a bigger bbox (possibly using extent function from raster package to read bbox of your spatial object and then enlarging it) and move the legend by adjusting its position.

This is what I came up with in a different context, but one which also called for a percentage sign in tmap legend. 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM