I have a rectangle in TikZ and the top left and bottom right corners are called (topleft) and (bottomright) respectively. I wanted to have a label midway down the left hand side of the rectangle, so I tried the following, both of which failed with cryptic error messages:
\draw let \p1 = (topleft), \p2 = (bottomright)
in (\x1,\pgfmathparse{0.5*(\y1 + \y2)}\pgfmathresult) node[right]{6 metres};
and
\draw let \p1 = (topleft), \p2 = (bottomright)
in (\x1,{0.5*(\y1 + \y2)}) node[right]{6 metres};
I got the desired result in a roundabout way:
\draw let \p1 = (topleft), \p2 = (bottomright)
in ($(\x1,\y1)!.5!(\x1,\y2)$) node[right]{6 metres};
But why did the first two attempts not work?
EDIT (in response to request for more detail):
If it helps, you can assume that the context of the command above is something like:
\usetikzlibrary{calc}
\begin{tikzpicture}
\draw (0,10) coordinate (topleft) rectangle (6,0) coordinate (bottomright);
%% relevant let statement would go just below here
\end{tikzpicture}
but I do not want a solution that uses the knowledge that the coordinates are (0,10) and (6,0).
Best Answer
Working with \pgfmathparse inside a path
If you need to do a calculation inside a path, I recommend to suspend this path, do the calculation, then resume the path. That "escaping" could be done by using the
\pgfextra{code}
macro executingcode
.In your example,
\pgfextra
may contain the\pgfmathparse
calculation,\pgfmathresult
may be used later on in the path.Here's the modification for your first example:
Output:
This advice is for the case that you need to do more complex calculation not easily done by simple expressions or perhaps intersections.