5

enter image description here

I have some code that will generate a new plot based on a random number. I'm having issues formatting the tick labels, however.

A few things I want to achieve:

  1. The y-tick label should always start at \N.
  2. I would always like 5 major ticks in the x and y axis.
  3. The gridlines/ticks should stop after the 5th major x/y tick but the axis arrow should continue for a small distance longer.
  4. The plot is rendering ".1.1" in the bottom left hand corner, which I want to get rid of.

Here is my MWE:

\documentclass{standalone}
\usepackage{pgfplots}
\usepackage{pgf}
\usetikzlibrary{calc}
\pgfplotsset{compat=1.11}

\begin{document}
\pgfmathsetmacro\N{random(1,1000)}
\pgfmathsetmacro\HL{random(0.1, 10)}
\begin{tikzpicture}

\begin{axis}[
xmin=0, xmax=5*\HL+0.1*\HL,
ymin=0, ymax=\N+0.1*\N,    
restrict y to domain=0:\N,
smooth,
samples = 20,
grid=both,
grid style={line width=.1pt, draw=gray!10},
major grid style={line width=.2pt,draw=gray!50},
axis lines=middle,
minor tick num=10,
axis line style={-latex},
ticklabel style={font=\tiny,fill=white},
]

\addplot[domain=0:5*\HL]  {\N*pow(0.5, x/\HL)};
\end{axis}
\end{tikzpicture}
\end{document}
2

If I understand you correctly, you do not want nice numbers for your tick marks (which would be much harder). Also, I had a problem with the FPU version of random(), so I created my own.

Note: Tikz does not as a rule run key options through \pgfmathparse, so at least there you need to put all math operations and even simple macros inside braces.

\documentclass{standalone}
\usepackage{pgfplots}
\usetikzlibrary{arrows.meta}
\pgfplotsset{compat=1.11}

\begin{document}
\tikzset{/pgf/declare function={myrandom(\a,\b)=\a+(\b-\a)*rnd;}}%
\pgfmathsetmacro\N{myrandom(1,1000)}%
\pgfmathsetmacro\HL{myrandom(0.1, 10)}%
\begin{tikzpicture}

\xdef\ylist{0.0}
\foreach \i in {0.2,0.4,0.6,0.8,1.0} {%
  \pgfmathparse{\i*\N}%
  \xdef\ylist{\ylist,\pgfmathresult}%
}
\xdef\xlist{0.0}
\foreach \i in {1,2,3,4,5} {%
  \pgfmathparse{\i*\HL}%
  \xdef\xlist{\xlist,\pgfmathresult}%
}
\begin{axis}[name=border,
xmin=0, xmax={5*\HL},
ymin=0, ymax={\N},    
%restrict y to domain=0:{\N},% not needed
ytick={\ylist},
xtick={\xlist},
smooth,
samples = 20,
grid=both,
grid style={line width=.1pt, draw=gray!10},
major grid style={line width=.2pt,draw=gray!50},
axis lines=middle,
minor tick num=10,
axis line style={-Butt Cap},
ticklabel style={font=\tiny,fill=white},
]
\addplot[domain=0:{5*\HL}]  {\N*pow(0.5, x/\HL)};
\end{axis}
\draw[-latex] (border.south east) -- +(5mm,0pt);
\draw[-latex] (border.north west) -- +(0pt,5mm);
\end{tikzpicture}
\end{document}

demo

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.