@@ -16,6 +16,56 @@ update_labels <- function(p, labels) {
1616 p
1717}
1818
19+ # Called in `ggplot_build()` to set default labels not specified by user.
20+ setup_plot_labels <- function (plot , layers , data ) {
21+ # Initiate from user-defined labels
22+ labels <- plot $ labels
23+
24+ # Find labels from every layer
25+ for (i in seq_along(layers )) {
26+ layer <- layers [[i ]]
27+ mapping <- layer $ computed_mapping
28+ mapping <- strip_stage(mapping )
29+ mapping <- strip_dots(mapping , strip_pronoun = TRUE )
30+
31+ # Acquire default labels
32+ mapping_default <- make_labels(mapping )
33+ stat_default <- lapply(
34+ make_labels(layer $ stat $ default_aes ),
35+ function (l ) {
36+ attr(l , " fallback" ) <- TRUE
37+ l
38+ }
39+ )
40+ default <- defaults(mapping_default , stat_default )
41+
42+ # Search for label attribute in symbolic mappings
43+ symbolic <- vapply(
44+ mapping , FUN.VALUE = logical (1 ),
45+ function (x ) is_quosure(x ) && quo_is_symbol(x )
46+ )
47+ symbols <- intersect(names(mapping )[symbolic ], names(data [[i ]]))
48+ attribs <- lapply(setNames(nm = symbols ), function (x ) {
49+ attr(data [[i ]][[x ]], " label" , exact = TRUE )
50+ })
51+ attribs <- attribs [lengths(attribs ) > 0 ]
52+ layer_labels <- defaults(attribs , default )
53+
54+ # Set label priority:
55+ # 1. Existing labels that aren't fallback labels
56+ # 2. The labels of this layer, including fallback labels
57+ # 3. Existing fallback labels
58+ current <- labels
59+ fallbacks <- vapply(current , function (l ) isTRUE(attr(l , " fallback" )), logical (1 ))
60+
61+ labels <- defaults(current [! fallbacks ], layer_labels )
62+ if (any(fallbacks )) {
63+ labels <- defaults(labels , current )
64+ }
65+ }
66+ labels
67+ }
68+
1969# ' Modify axis, legend, and plot labels
2070# '
2171# ' Good labels are critical for making your plots accessible to a wider
@@ -144,8 +194,13 @@ get_alt_text <- function(p, ...) {
144194# ' @export
145195get_alt_text.ggplot <- function (p , ... ) {
146196 alt <- p $ labels [[" alt" ]] %|| % " "
197+ if (! is.function(alt )) {
198+ return (alt )
199+ }
147200 p $ labels [[" alt" ]] <- NULL
148- if (is.function(alt )) alt(p ) else alt
201+ build <- ggplot_build(p )
202+ build $ plot $ labels [[" alt" ]] <- alt
203+ get_alt_text(build )
149204}
150205# ' @export
151206get_alt_text.ggplot_built <- function (p , ... ) {
0 commit comments