3

I have the following MWE:

\documentclass{standalone}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{filecontents}
\pgfplotsset{compat=1.12}

\begin{filecontents}{data.dat}
4 -1e4
4 -1e3
4 -1e2
4 -10
4 -1
\end{filecontents}

\begin{document}
\begin{tikzpicture}
    \begin{axis}[
            xmin=0, xmax=5
        ]
        \addplot table {data.dat};
    \end{axis}
\end{tikzpicture}
\end{document}

This produces the following plot:

A normally scaled plot

Now I'd like to have ticks on the y axis at -1e0, -1e1, -1e2, -1e3 and -1e4 with even spacing. If my values are positive, I can achieve this by adding ymode=log to the axis options, but for negative values this just produces an error.

So how can I produce a sort of logarithmic scale for negative values?

4
  • 1
    Is there a log for negative values at all? I mean mathematically! I think this is not possible, independent of pgfplots. Try it with your calculator: log(-1) is not defined. May 17, 2016 at 21:35
  • 2
    Not in the real numbers, that's why I'm calling it a "sort of" logarithmic plot. I don't really care if the term is accurate or not, I just want a scale that looks like a logarithmic one but mirrored over the x axis.
    – jazzpi
    May 17, 2016 at 21:38
  • log(-1) = j pi since e^(j pi) = cos(pi) + j sin(pi) = -1 + j 0 = -1, but this is obviously worthless for this plot. I just want a scale that looks like a logarithmic one.
    – jazzpi
    May 17, 2016 at 21:42
  • sign(x)log(abs(x)) is totally valid
    – Mageek
    Jan 6, 2021 at 5:17

1 Answer 1

5

This works, but requires copious manual intervention. Note, in this case [ytick=data] would achieve the same effect, but in general you can't count on that.

\documentclass{standalone}
\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{filecontents}
\pgfplotsset{compat=1.12}

\begin{filecontents}{data.dat}
x y
4 -1e4
4 -1e3
4 -1e2
4 -10
4 -1
\end{filecontents}

\begin{document}
% create column "log"
\pgfplotstableread{data.dat}\table
\pgfplotstablecreatecol[create col/expr={-log10(-\thisrow{y})}]{log}\table
%\pgfplotstabletypeset\table
\begin{tikzpicture}
    \begin{axis}[ytick={-4,-3,-2,-1,-0},yticklabels={-1e4,-1e3,-1e2,-10,-1},
            xmin=0, xmax=5
        ]
        \addplot table[x=x, y=log] \table;
    \end{axis}
\end{tikzpicture}
\end{document}

demo

2
  • I suppose that works sort of, but the y axis is inverted and my dataset has 402 entries so this would be a lot of work... There has to be a more elegant way.
    – jazzpi
    May 18, 2016 at 8:39
  • I revised the solution to automate new column creation. May 18, 2016 at 14:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .