I'm having trouble with a variable set with \pgfmathsetmacro in a loop within an axis environment. Only the last value of the variable is being printed during each loop iteration. In the code below, the values in the rectangles are supposed to be displaying the distance between the upper and lower graphs, but all the values are showing the distance between the graphs in the last rectangle. I've searched extensively online for a solution but can't determine how to implement any of them successfully. Hence, I'm hoping some kind soul can show me the path forward. Below is my code:
Code: Select all
Code, edit and compile here:
\documentclass[border=10pt]{standalone}\usepackage{tikz}\usepackage{pgfplots}\pgfplotsset{compat=1.18}\pgfplotsset{tick label style={font=\scriptsize},minor x grid style={gray, opacity=0.25}}\tikzstyle{every node}=[font=\scriptsize]\begin{document}\begin{tikzpicture}[declare function={f(\x)=0.73*pow(\x,3)-2*pow(\x,2)+\x+0.6;g(\x)=0.17*pow(\x,2)-0.5*\x+1.1;},]\begin{axis}[grid=both,xmin=0, xmax=2, xtick distance=0.2,minor x tick num=1,ymin=0, ymax=1.2, ytick distance=0.1,xlabel={$t$ (hours)}, ylabel={$r$ (inches/hour)}]\addplot[thick, smooth, domain=0:2]{0.73*x^3-2*x^2+x+0.6}node[below left, pos=0.45] {$r = f(t)$};\addplot[thick, smooth, domain=0:2]{0.17*x^2-0.5*x+1.1}node[above, pos=0.7] {$r = g(t)$};\pgfplotsinvokeforeach{0.2,0.6,...,1.8}{\pgfmathparse{g(#1+0.1)-f(#1+0.1)};\pgfmathsetmacro{\ans}{\pgfmathresult};\draw[thick](#1,{f(#1+0.1)}) rectanglenode[anchor=center,rotate=90,font=\small\sffamily\bfseries]{\pgfmathprintnumber[precision=4]{\ans}} (#1+0.2,{g(#1+0.1)});};\end{axis}\end{tikzpicture}