How do I specifically control the size of color key bar, present on the right side of plot of a raster file?

35 views Asked by At

I wish to make contour plots of netcdf files. I first extract the nc files and make them into raster format (easier to plot). The plots come fine, but I want to scale up the size of the color key bar present on the right side.

Here is my R script:

lapply(c("ncdf4","raster","sf","Metrics"),require,character.only=TRUE)

setwd("~/Desktop/Feb_24")

border <- read_sf("India_boundary/India_Boundary.shp")
ncfile <- nc_open("monthwise/ACCESS-CM2_historic_monmean.nc")

wsp_mod <- ncvar_get(ncfile,varid="sfcWind")

pal <- colorRampPalette(c("darkblue","blue","cyan","green","yellow","orange","red"))

for(i in seq(1:12)){
  
  r_mon <- raster(wsp_mod[,,i])
  r_mon <- t(flip(r_mon,1))
  r_mon@extent <- extent(65.125,100.125,3.125,40.125)
  r_mon <-mask(crop(r_mon,extent(border)),border)
  r_mon@title <-"Multi year monthly mean"
  
  png(filename=paste(i,"_ACCESS-CM2_historic.png"),width=1400,height=1400)
  par(mar=c(5,6,4,1)+.1)
  plot(r_mon,xlab="Longitude",ylab="Latitude",main=paste(i),cex.lab=1.3,cex.axis=1.2,cex.main=1.3,col=pal(8),breaks=c(0,1,2,3,4,5,6,7,8))
  lines(border,col="black")
  dev.off()

}

the arguments, cex.lab, cex.axis, cex.main, do not scale up the color key bar. I have searched throughout the documentation to find a parameter that controls this size but in vain. Do let me know if theres a way to specifically control the size of the color bar.

2

There are 2 answers

0
Grzegorz Sapijaszko On

If you are using raster::plot() then use legend.width parameter, like:

s <- raster::stack("download.nc")

s[[1]] |>
  raster::plot()


s[[1]] |>
  raster::plot(legend.width = 2.5)

Created on 2024-03-05 with reprex v2.1.0

0
Robert Hijmans On

When asking an R question please include a minimal, self-contained, reproducible example. Here is one:

library(terra)
f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)
plot(r)

To get a larger font size you can do

plot(r, plg=list(cex=1.5))

To also make the legend wider, you can do

plot(r, plg=list(cex=1.5, size=c(1,2)))

As a bonus, here is your code rewritten with terra, the replacement of the raster package.

library(terra)
border <- terra::vect("India_boundary/India_Boundary.shp")
x <- terra::rast("monthwise/ACCESS-CM2_historic_monmean.nc", "sfcWind")
pal <- colorRampPalette(c("darkblue","blue","cyan","green","yellow","orange","red"))
extent <- terra::ext(65.125,100.125,3.125,40.125)
m <- terra::mask(terra::crop(x, extent), border)

for (i in 1:nlyr(m)) {
  png(filename=paste(i,"_ACCESS-CM2_historic.png"),width=1400,height=1400)
  par(mar=c(5,6,4,1)+.1)
  plot(m[[i]], xlab="Longitude", ylab="Latitude", main=i, cex.lab=1.3, cex.axis=1.2, cex.main=1.3, col=pal(8), breaks=c(0,1,2,3,4,5,6,7,8))
  lines(border,col="black")
  dev.off()
}