Skip to content

Commit 69f127d

Browse files
committed
user proper key widths, stop() if there's not enough space
see also r-spatial/stars#642
1 parent ebf336c commit 69f127d

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

NEWS.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# version 1.0-15
22

3-
* `plot.sf()`: `key.width` is sensitive to pointsize graphics parameter, `key.pos` can hold a second value in [0, 1] determining the relative position of the key in the available space
3+
* `plot.sf()`: `key.width` is sensitive to pointsize graphics parameter, `key.pos` can hold a second value in [0, 1] determining the relative position of the key in the available space; keys with factor levels suggest a proper size if they won't fit.
44

55
* `[<-.sf` fixes the `agr` attribute when it is broken; #2211
66

R/plot.R

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -896,8 +896,7 @@ xy_from_r = function(r, l, o) {
896896
..., axes = FALSE, key.width, key.length, cex.axis = par("cex.axis")) {
897897

898898
n = length(z)
899-
# TODO:
900-
ksz = as.numeric(gsub(" cm", "", key.width)) * 2
899+
ksz = max(strwidth(z, "inches")) / par("cin")[1] # in "mar" lines
901900
breaks = (0:n) + 0.5
902901
offset = 0.5
903902
if (length(key.pos) == 2) {
@@ -921,15 +920,24 @@ xy_from_r = function(r, l, o) {
921920
ylim = xy_from_r(range(breaks), key.length, offset)
922921
xlim = c(0, 1)
923922
mar = c(ifelse(axes, 2.1, 1), 0, 1.2, 0)
924-
mar[key.pos] = max(ksz - 1.3, 0.0)
923+
mar[key.pos] = ksz
925924
}
926925
par(mar = mar)
927926

928927
poly = vector(mode="list", length(col))
929928
for (i in seq(poly))
930929
poly[[i]] = c(breaks[i], breaks[i+1], breaks[i+1], breaks[i])
931-
plot(1, 1, t = "n", ylim = ylim, xlim = xlim, axes = FALSE,
932-
xlab = "", ylab = "", xaxs = "i", yaxs = "i")
930+
931+
tryCatch({
932+
plot(1, 1, t = "n", ylim = ylim, xlim = xlim, axes = FALSE,
933+
xlab = "", ylab = "", xaxs = "i", yaxs = "i")
934+
},
935+
error = function(x) {
936+
sz = max(strwidth(z, "inches")) * 2.54 + par("ps")/12 # cm
937+
stop(paste0("key.width too small, try key.width = lcm(", signif(sz, 3), ")"), call. = FALSE)
938+
}
939+
)
940+
933941
for(i in seq_along(poly)) {
934942
if (key.pos %in% c(1,3))
935943
polygon(poly[[i]], c(0, 0, 1, 1), col = col[i], border = NA)

0 commit comments

Comments
 (0)