I'm trying to use the text data from a table column as the tick labels in a plot. The text data contains underscores, which makes LaTeX throw a Missing $ inserted
error. I'd usually get around this by loading the underscore
package, and that works fine if I provide the list of tick labels explicitly using xticklabels={A_B,B_C}
. However, when I use the xticklabels from table={<table name>}{<column name>}
syntax, the underscores are not printed and I get the Missing $
error again.
I looked at what the the xticklabels from table
option does, and basically it just reads the specified table column, writes the content into a list, and then unpacks that list for each tick, using the following macro:
\makeatletter
\def\pgfplots@user@ticklabel@list@x{%
\pgfplotslistselectorempty\ticknum\of\pgfplots@xticklabels\to\tick
\tick
}
\makeatother
\pgfplots@xticklabels
is the list that the labels were stored into, and \tick
is just a macro that holds the label text for a single tick. Using \show\tick
in that macro shows that it really just holds the plain text:
> \tick=macro:
->A_B.
Now ordinarily, that should just work. If I say \def\testtext{_}
and then I print that text using another macro, say \def\printtest{\testtext} \printtest
, the underscore shows up.
How can I use underscores in ticklabels specified using xticklabels from table
without having to replace the underscores in the data table with \_
?
\documentclass{article}
\usepackage{underscore}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
%% For your convenience: This is the unaltered macro that prints
%% the tick label when "xticklabels from table" is used
\makeatletter
\def\pgfplots@user@ticklabel@list@x{%
\pgfplotslistselectorempty\ticknum\of\pgfplots@xticklabels\to\tick
\tick
}
\makeatother
\pgfplotstableread{
Label Value_A
A_B 1
B_C 2
}\datatable
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xtick=data,
% xticklabels={A_B,B_C}, % <- this works
xticklabels from table={\datatable}{Label} % <- this doesn't
]
\addplot table[x expr=\coordindex]{\datatable};
\end{axis}
\end{tikzpicture}
\end{document}
$\tick$
would do the job... hm.\begin{document}
an essential part of the request? After all, the modifications ofunderscore
are ineffective before\begin{document}
, so the table data has "raw" underscore values. If you move\pgfplotstableread
after\begin{document}
, everything works well.\pgfplotstableread
command after\begin{document}
, but I still get errors with the underscore in the column name. The underscores in the "Label" column work fine though, so that's at least a partial success.underscore
is not expandable.