rplotrix

recover from R plotrix forcing the label to '1' if the population plot has one entry


So I have this weird behaviour illustrated in the two MWE examples below

library(plotrix)
pyramid.plot(c(10,5),
             c(7,5),
             labels=c("test","test1"),
)

enter image description here The label prints as expected when you have two or more entries for the lx and rx bars. But when you have one entry the label gets turned to "1" in the resulting plot.

library(plotrix)
pyramid.plot(10,
             5,
             labels="test",
)

enter image description here The doc says "There should be a label for each lx or rx value", which does not describe why when that value is one entry plotrix replaces "test" to 1. I looked at the sourcecode and this line appears to be where the problem is. I appreciate any clues to how to bypass this and restore the expected behaviour.

ncats <- ifelse(!is.null(lxdim), dim(lx)[1], length(lx))
    if (length(labels) == 1) 
        labels <- 1:ncats

My hacky workaround badly places the label to the lx side and I do not want to switch away from a base R solution.

library(plotrix)
pyramid.plot(10,
             5,
             labels=matrix(c("test",NA), nrow=1),
)

Solution

  • The best way to do this is probably to make your own copy of the function and edit it to eliminate this test (to be honest I'm not sure of the original intent of the test, so I don't know how/whether it should be modified in general ...)

    A cheap hack is to modify the function on the fly. This is fragile because it will break if the structure of the function is changed upstream ...

    fun_test <- deparse(body(pyramid.plot))
    target <- grep("length(labels) ==", fun_test, fixed = TRUE)
    fun_test[target+(0:1)] <- paste0("#", fun_test[target+(0:1)])
    my_pp <- function() {}
    formals(my_pp) <- formals(pyramid.plot)
    body(my_pp) <- parse(text = fun_test)
    
    my_pp(10,
                 5,
                 labels="test"
    )