Search code examples
rmschartofficer

Percentage format for y axis in mschart


Ok, this is kind of driving me insane. Hopefully I'm just stupid and someone can point me to the right answer quickly. I'm trying to format the y-axis to be a percent rather than a number. Here is a simple example ...

library(officer)
library(mschart)
data = data.frame(x = c(1, 1, 2, 2, 3, 3),
                  y = c(.05, .05, .06, .06, .07, .07),
                  group = c("A", "B", "A", "B", "A", "B"))

output <- data %>%
  ms_barchart(x = "x", y = "y", group = "group") %>%
  chart_settings(dir = "vertical") %>%
  chart_data_labels(show_val = TRUE, show_legend_key = FALSE, num_fmt = "0.00%") %>%
  chart_labels(title = " ", xlab = " ", ylab = " ")  %>%
  chart_ax_y(display = TRUE, limit_min = 0, num_fmt = "0.00") %>%
  chart_ax_x(major_tick_mark = "none")

doc <- read_pptx()
doc <- add_slide(doc, layout = "Title and Content", master = "Office Theme")
doc <- ph_with(doc, output, location = ph_location_fullsize())
print(doc, paste0(file.path(path.expand('~'),'Desktop'),"/num_fmt.pptx"))

The above code will not produce an error, but the format is not as desired.

Using num_fmt = "0.00%" in the chart_ax_y function produces the error when attempting to print the pptx file: Error in sprintf(str_, id, cross_id) : invalid format '%" s'; use format %s for character objects

Using num_fmt = "0.00\%\%" (this is what the mschart documentation says to do) in the chart_ax_y function produces the following error when trying to create the output object: Error: '\%' is an unrecognized escape in character string starting ""0.00\%"

Please help!


Solution

  • From a little experimentation from @Jessica and some older references on mschart package, looks like the documentation on CRAN is just in error, and the backslashes aren't supposed to appear, although the percentage signs are to be repeated.

    chart_ax_y(display = TRUE, limit_min = 0, num_fmt = "0.00%%")
    

    Another reference link on mschart: how to resize plot area in R mschart