Question

I usually use the scales package in R to give percentages on counts data on the y axis of my ggplots. When I try to do this in knitr, however, I get an error because of the percentage symbol on the plot:

Error in getMetricsFromLatex(TeXMetrics) : TeX was unable to calculate metrics for the following string or character: 0%

I can survive with the normal counts axis, but would prefer the %. Is there a way around this?

Here is a reproducible example (removing + scale_y_continuous(label=percent) gives a compilable example):

\documentclass[11pt]{article}
\usepackage{tikz}

\begin{document} 
<<packages, echo=F>>=
    library(ggplot2)
    library(scales)
@
<<chunkopts, echo=F>>=
    opts_chunk$set(echo=F, cache=T,  autodep=T, fig.width = 9/1.5, fig.height=5/1.5,
    fig.align="center", dev="tikz", fig.pos="h!tbp", warning=F, message=F)
    dep_auto()
@
<<mydata>>=
    mydata <- data.frame(
      X = letters[1:10],
      Y = sample(c("yes", "no"), 100, replace = TRUE))
@
<<plot>>=
     ggplot(mydata, aes(X, fill = Y)) +  geom_bar(position = "fill") +
             scale_y_continuous(label=percent)
@
\end{document}

I'm using TexShop to compile my .Rnw files.

Was it helpful?

Solution

The problem is that % is a special character in latex and it needs escaping. Try the following alternative scale

library(stringr)
library(plyr)
latex_percent <- function (x) {
    x <- plyr::round_any(x, scales:::precision(x)/100)
    stringr::str_c(comma(x * 100), "\\%")
}

and replace labels=percent with labels=latex_percent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top