5

Is it possible in latex to directly round off numbers from tables before plotting? I tried using round-precision from siunitx package, but this does not seem to work. MWE

    \documentclass{standalone}
    \usepackage{pgfplots}
    \usepackage{pgfplotstable}
    \pgfplotsset{compat=newest}
    \usepackage{siunitx}
    \begin{document}
    \begin{tikzpicture}
    \begin{axis}[
      xlabel= x,
      ylabel=y]
    \addplot[only marks, color=black,mark=square*] table [y=y[round-precision=0], x=x]{test.txt};
    \end{axis}
    \end{tikzpicture}
    \end{document}

The data table

x   y
1   1.2
2   1.56
3   1.559
4   1.07

1 Answers1

7

This is a common problem with pgfplots (or tikz in general), that you cannot round numbers prior to printing them. But here we need to fully-expandably round the numbers, which can be done with l3fp.

I declared the macro \round[<precision>]{<expression>} which rounds expression to precision decimal digits. The precision argument is optional and defaults to 0, i.e. round to nearest integer.

\begin{filecontents*}{test.txt}
x   y
1   1.2
2   1.56
3   1.559
4   1.07
\end{filecontents*}
\documentclass{standalone}
\usepackage{pgfplots,xparse}
\ExplSyntaxOn
\DeclareExpandableDocumentCommand \round { O{0} m }
 { \fp_eval:n { round(#2,#1) } }
\ExplSyntaxOff
\begin{document}
\begin{tikzpicture}
  \begin{axis}[xlabel=$x$,ylabel=$y$,only marks]
    \addplot table [x=x,y=y]{test.txt};
    \addplot table [x=x,y expr={\round[1]{\thisrow{y}}}]{test.txt};
    \legend{bare,rounded}
  \end{axis}
\end{tikzpicture}
\end{document}

enter image description here

Henri Menke
  • 109,596