Skip to content

Unconstrained margins in sf::plot()? #2558

@courtiol

Description

@courtiol

The "simple" plot() function in sf does not seem to let the user define margins.
This is hard-coded here:

sf/R/plot.R

Lines 304 to 309 in a3de3df

if (!isTRUE(dots$add)) {
mar = c(1, 1, 1.2, 1)
if (isTRUE(dots$axes))
mar[1:2] = 2.1
par(mar = mar)
}

So unless I am wrong, any attempt to define par(mar = c(...)) beforehand, or to define mar = c(...) when calling plot(), will fail.

This can be problematic even in simple cases, e.g.:

library(sf)
#> Linking to GEOS 3.14.1, GDAL 3.11.5, PROJ 9.6.2; sf_use_s2() is TRUE
nc <- st_read(system.file("gpkg/nc.gpkg", package="sf"), quiet = TRUE)
plot(nc["SID74"], graticule = TRUE, axes = TRUE, las = 1, main = "A double line\ntitle")

One can use grid "black magic" to get around the constraint, but it is not quite user friendly...

plot(nc["SID74"], graticule = TRUE, axes = TRUE, las = 1, main = "")
p <- recordPlot()
gridGraphics::grid.echo() # needed (for side effect)
a <- grid::grid.grab()
grid::grid.newpage()
a <- grid::editGrob(a, vp = grid::viewport(width = 0.8, height = 0.9))
grid::grid.draw(a)
grid::grid.text("A double line\ntitle", y = grid::unit(0.95, "npc"))

Created on 2025-11-30 with reprex v2.1.1

Of course, there is always the ggplot way out, but passing a mar argument to plot would be a very welcome addition to plot().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions