2

could help me to get a macro to draw such axis if I specify :

  • the beginning and the end of the axis (not necessarily integers)
  • how it should be graduated
  • a list of points with coordinates and names

Here are two examples :

    \begin{tikzpicture}[scale=1.2]
    \draw[->] (0,0) --(7.2,0);
    \foreach \x in {0,...,70}{\draw [color=violet](\x/10,0.1)--(\x/10,-0.1);}
    \foreach \x in {0,1,...,7}{\draw[thick] (\x,0.2)--(\x,-0.2);\node at (\x,0.4) {$\x$};}

    \node at (2.4,-0.6) {$A$};
    \draw[->] (2.4,-0.4)--(2.4,-0.1) {};

    \node at (5.7,-0.6) {$B$};
    \draw[->] (5.7,-0.4)--(5.7,-0.1) {};
    \end{tikzpicture}

or

    \begin{tikzpicture}[scale=1]
    \draw[->] (0,0) --(10.2,0);
    \draw[thick] (0,0.4)--(0,-0.4);
    \node at (0,0.8) {$3$};
    \foreach \x in {0,...,99}{\draw[thin]  [color=blue](\x/10,0.1)--(\x/10,-0.1);}
    \foreach \x in {1,...,9}{\draw [color=violet](\x,0.2)--(\x,-0.2);}
    \draw[thick] (10,0.4)--(10,-0.4);\node at (10,0.8) {$4$};
    \node at (2.4,-0.6) {$E$};
    \draw[->] (2.4,-0.4)--(2.4,-0.1) {};
    \node at (5.7,-0.6) {$D$};
    \draw[->] (5.7,-0.4)--(5.7,-0.1) {};
    \end{tikzpicture}

Thanks

AndréC
  • 24,137
jadou
  • 213

1 Answers1

4

This is what I currently use:

\tikzset{
  axis/.style={
    ultra thick,
  },
  grid/.style={
    help lines,
    draw
  },
  pics/axes/.style args={#1:#2;#3:#4}{
    code = {
      \path[grid] (#1-.5,#3-.5) grid (#2+.5,#4+.5);
      \draw[->,axis] (#1 - .5,0) -- (#2 + .5,0);
      \draw[->,axis] (0,#3 - .5) -- (0,#4 + .5);
      \foreach \x in {#1,...,#2} {
        \ifnum\x=0\else
        \draw[axis] (\x,0) -- (\x,-.2);
        \node[below left] at (\x+.1,-.2) {\(\x\)};
        \fi
      }
      \node[below] at (#2+.5,-.2) {\(\pgfkeysvalueof{/tikz/pics/axes/x label}\)};
      \foreach \y in {#3,...,#4} {
        \ifnum\y=0\else
        \draw[axis] (0,\y) -- (-.2,\y);
        \node[below left] at (-.1,\y) {\(\y\)};
        \fi
      }
      \node[left] at (-.1,#4+.5) {\(\pgfkeysvalueof{/tikz/pics/axes/y label}\)};
      \node[below left] at (0,0) {0};
    }
  },
  pics/axes/.default={-6:6;-6:6},
  pics/axes/x label/.initial=x,
  pics/axes/y label/.initial=y,
}

Use in:

\pic{axes=0:4;0:4};
AndréC
  • 24,137
Andrew Stacey
  • 153,724
  • 43
  • 389
  • 751
  • @AndréC Ooops! I missed out a couple of keys. Thanks for the catch. – Andrew Stacey Oct 01 '19 at 20:02
  • I get "Undefined control sequence. \pics" with your code. – jadou Oct 03 '19 at 07:55
  • @jadou That's an odd error message since \pics isn't used. If the error said \pic, it might be because you have to put it in a tikzpicture environment, ot it might be because your version of pgf is old. – Andrew Stacey Oct 03 '19 at 23:19