6

I would like to add a main diagonal to a plot that does not affect the axis. The line should start and end at the axis or beyond them. Furthermore, I would like to avoid xminand xmax, because I work with data tables. I tried relative coordinates rel axis cs, but this does not result in a main diagonal (slope 1 and offset 0). Here is a minimal working example to start with:

\documentclass{scrartcl}

\usepackage{pgfplots}
\pgfplotsset{compat=1.9}

\begin{document}

\begin{tikzpicture}
    \centering
    \pgfplotsset{width=0.9\columnwidth}
    \begin{axis}
        \addplot coordinates {(0,0.1)(1,2)(2,3)};
    \end{axis}
\end{tikzpicture}

\end{document}
5
  • 2
    This looks similar: tex.stackexchange.com/questions/55718/…. You can use axiscs in combination with \pgfkeysvalueof{/pgfplots/xmin} and variants to produce the main diagonal. I believe this will only work if you draw the line after your plot your data. – sudosensei Nov 29 '13 at 9:40
  • By 'main diagonal', do you mean a line with slope 1 passing through the origin? – Jake Nov 29 '13 at 10:38
  • @sudosensei: It is similar, but I do not want to specify xmin and xmax, because my data comes from tables that can change. @Jack Yes, slope 1 and no offset. – Dirk Nov 29 '13 at 11:01
  • Oh, I misunderstood the question. Apologies. I have deleted my answer. You are in good hands with Jake. He's helped me countless times so far. :-) – sudosensei Nov 29 '13 at 11:08
  • No problem. However, your answer gives me the correct hint to solve the problem, as you see in my answer. – Dirk Nov 29 '13 at 14:27
7

Thanks for the hint to percuss's excellent answer, sudosensei! From his code I derived the following one:

\draw[red]
(axis cs:\pgfkeysvalueof{/pgfplots/xmin},\pgfkeysvalueof{/pgfplots/xmin}) -- 
(axis cs:\pgfkeysvalueof{/pgfplots/xmax},\pgfkeysvalueof{/pgfplots/xmax});

This solves my problem: enter image description here

Complete code:

\documentclass{scrartcl}

\usepackage{pgfplots}
\pgfplotsset{compat=1.9}

\begin{document}

\begin{tikzpicture}
    \centering
    \pgfplotsset{width=0.9\columnwidth}
    \begin{axis}
        \addplot coordinates {(0,0.1)(1,2)(2,3)};
        \draw[red]
            (axis cs:\pgfkeysvalueof{/pgfplots/xmin},\pgfkeysvalueof{/pgfplots/xmin}) -- 
            (axis cs:\pgfkeysvalueof{/pgfplots/xmax},\pgfkeysvalueof{/pgfplots/xmax});
    \end{axis}
\end{tikzpicture}

\end{document}
1
  • For the sake of completeness: Use \addlegendimage{line legend, red}\addlegendentry{Theory} to add a legend to the red line. – Dirk Nov 30 '13 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.