From df5cd0c4eef0b6ab4c480c88c0c58160c7ae4cac Mon Sep 17 00:00:00 2001 From: Nicholas Clark Date: Wed, 8 Nov 2023 13:27:26 +1000 Subject: [PATCH] better rounding of labels in cond_effects() --- R/conditional_effects.R | 41 +++++++++++++++++++++++++++++++++++++--- src/mvgam.dll | Bin 1064960 -> 1064960 bytes 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/R/conditional_effects.R b/R/conditional_effects.R index 155be3f4..a405431d 100644 --- a/R/conditional_effects.R +++ b/R/conditional_effects.R @@ -112,7 +112,9 @@ conditional_effects.mvgam = function(x, type = type, points = points, rug = rug, - ...) + ...) + + scale_fill_discrete(label = roundlabs) + + scale_colour_discrete(label = roundlabs) } @@ -124,7 +126,9 @@ conditional_effects.mvgam = function(x, type = type, points = points, rug = rug, - ...) + ...) + + scale_fill_discrete(label = roundlabs) + + scale_colour_discrete(label = roundlabs) } if(length(cond_labs[[i]]) == 3){ @@ -136,7 +140,9 @@ conditional_effects.mvgam = function(x, type = type, points = points, rug = rug, - ...) + ...) + + scale_fill_discrete(label = roundlabs) + + scale_colour_discrete(label = roundlabs) } @@ -169,6 +175,35 @@ plot.mvgam_conditional_effects = function(x, invisible(out) } +#' A helper function so ggplot2 labels in the legend don't have +#' ridiculous numbers of digits for numeric bins +#' @noRd +decimalplaces <- function(x) { + x <- as.numeric(x) + if (abs(x - round(x)) > .Machine$double.eps^0.5) { + nchar(strsplit(sub('0+$', '', as.character(x)), ".", + fixed = TRUE)[[1]][[2]]) + } else { + return(0) + } +} + +#' A helper function so ggplot2 labels in the legend don't have +#' ridiculous numbers of digits for numeric bins +#' @noRd +roundlabs = function(x){ + if(all(suppressWarnings(is.na(as.numeric(x))))){ + out <- x + } else if(all(sapply(x, decimalplaces) == 0)) { + out <- x + }else if(all(sapply(x, decimalplaces) <= 1)) { + out <- sprintf("%.1f", as.numeric(x)) + } else { + out <- sprintf("%.4f", as.numeric(x)) + } + out +} + #' @rdname conditional_effects.mvgam #' @export print.mvgam_conditional_effects <- function(x, ...) { diff --git a/src/mvgam.dll b/src/mvgam.dll index 42c0b2d5b17252ac8b7cc3c2a381d954b27503d4..1e4f45009ff40cf961b8c020b1d2fd911cce4024 100644 GIT binary patch delta 78 zcmWm5y$wJ>0EXdkI6uc(!x&nL0c>-MFOg^%Mhx@T>>yEyr+-4|L+H1~yzj8Dqj73y gL?mKiL?Tj=2`h3@h*DI-iCQ!VzPtW=+S@Px# delta 78 zcmZo@aBOIBoY29Xe%^Cpw=eU3O~J<7t+yFlZ!@*tW^TRB(t4Y<^)_4UZT8mN9IdxG iTW@o<-sWz-&C`0DxAivP*4zA=PeFROvp?hi83_PxuOr(4