[Tex/LaTex] How to use underscores with pgfplotstable

pgfplotstable

I have an input file like this:

some_entry 123
another_entry 456
yet_another_entry 789

and I want to typeset it as a table with:

\pgfplotstabletypeset[col sep=space]{FILENAME}

Problem is that LaTeX seems to interpret the underscores as a command to typeset subscript.

Escaping the underscores in the input file does not work.

Best Answer

Here is a solution for the problem which works without category codes:

\documentclass{standalone}

\usepackage{pgfplotstable}

\begin{document}
\pgfplotstabletypeset[
  header=false,
  columns/0/.style={
    string type,
    postproc cell content/.code={%
        \pgfplotsutilstrreplace{_}{\_}{##1}%
        \pgfkeyslet{/pgfplots/table/@cell content}\pgfplotsretval
    },
  },
  ]{
some_entry 123
another_entry 456
yet_another_entry 789
}
\end{document}

enter image description here

the solution is based on the following observations:

  1. you do not really have column names, right? I added header=false which causes pgfplotstable to assign column indices as names (starting with 0).

  2. Your first column is of string type and not a number, so I added that as style.

  3. This is, of course, the key part: LaTeX (not pgfplotstable) interpretes _ as math mode subscript token. So: we have the choice to render the entire text in math mode (not what we want) or we replace the subscript token by a suitable text token. That's what I did: I added a postprocessor which applies string search-and-replace: it replaces _ by \_.

The approach works for both inline tables and input files.


Note that the story would be slightly different if you had column names containing underscores - in this case, you would need to add column name such that the column name is typeset correctly and our example would become:

\documentclass{standalone}

\usepackage{pgfplotstable}

\begin{document}
\pgfplotstabletypeset[
  columns/A_d/.style={
    string type,
    column name=$A_d$,
    postproc cell content/.code={%
        \pgfplotsutilstrreplace{_}{\_}{##1}%
        \pgfkeyslet{/pgfplots/table/@cell content}\pgfplotsretval
    },
  },
  ]{
  A_d B
some_entry 123
another_entry 456
yet_another_entry 789
}
\end{document}

enter image description here

This works because math mode _ are actually expandable, so they can be part of column names.

Related Question