Skip to content

Commit c8302dc

Browse files
committed
handle factors correctly
1 parent 83c05fd commit c8302dc

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed

R/sf.R

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -457,13 +457,14 @@ CoordSf <- ggproto("CoordSf", CoordCartesian,
457457
x_labels <- scale_x$labels
458458
}
459459

460-
if (is.character(x_labels)) {
460+
# all labels need to be temporarily stored as character vectors,
461+
# but expressions need to be parsed afterwards
462+
if (is.character(x_labels) || is.factor(x_labels)) {
461463
needs_parsing[graticule$type == "E"] <- FALSE
462464
} else {
463-
# all labels need to be temporarily stored as character vectors
464-
x_labels <- as.character(x_labels)
465465
needs_parsing[graticule$type == "E"] <- TRUE
466466
}
467+
x_labels <- as.character(x_labels)
467468
}
468469

469470
if (length(x_labels) != length(x_breaks)) {
@@ -485,13 +486,14 @@ CoordSf <- ggproto("CoordSf", CoordCartesian,
485486
y_labels <- scale_y$labels
486487
}
487488

488-
if (is.character(y_labels)) {
489+
# all labels need to be temporarily stored as character vectors,
490+
# but expressions need to be parsed afterwards
491+
if (is.character(y_labels) || is.factor(y_labels)) {
489492
needs_parsing[graticule$type == "N"] <- FALSE
490493
} else {
491-
# all labels need to be temporarily stored as character vectors
492-
y_labels <- as.character(y_labels)
493494
needs_parsing[graticule$type == "N"] <- TRUE
494495
}
496+
y_labels <- as.character(y_labels)
495497
}
496498
if (length(y_labels) != length(y_breaks)) {
497499
stop("Breaks and labels along y direction are different lengths", call. = FALSE)

tests/testthat/test-coord_sf.R

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,30 @@ test_that("axis labels can be set manually", {
6060
c("D", "E", "F")
6161
)
6262

63+
# factors are treated like character labels
64+
# and are not parsed
65+
b <- ggplot_build(
66+
plot +
67+
scale_x_continuous(
68+
breaks = c(1000, 2000, 3000),
69+
labels = factor(c("A", "B", "C"))
70+
) +
71+
scale_y_continuous(
72+
breaks = c(1000, 1500, 2000),
73+
labels = factor(c("1 * degree * N", "1.5 * degree * N", "2 * degree * N"))
74+
)
75+
)
76+
graticule <- b$layout$panel_params[[1]]$graticule
77+
expect_identical(
78+
graticule[graticule$type == "E", ]$degree_label,
79+
c("A", "B", "C")
80+
)
81+
expect_identical(
82+
graticule[graticule$type == "N", ]$degree_label,
83+
c("1 * degree * N", "1.5 * degree * N", "2 * degree * N")
84+
)
85+
86+
6387
# expressions mixed with character labels
6488
b <- ggplot_build(
6589
plot +

0 commit comments

Comments
 (0)