I'm beginning to use TikZ and am having some issues understanding the proper way to reference my data points without specifying the precise absolute positions for all of them. An example of the simple situation I'm confused with is as follows:
Let's say I have 3 points, A=(ax,ay)
, B=(bx,by)
and C=(bx,by-1)
. I want to draw lines between these points, but I also want them to be labelled A, B and C so that I may refer to them later. If I simply define my points A and B like so:
\coordinate (A) at (ax,ay);
\coordinate (B) at (bx,by);
then what is the best way to get C? Should I try something like
\coordinate (C) at "some way of referring to B's coordinates and doing math on them"
or do I have to use some (seemingly) clumsy statement like
\coordinate (C) at let \p1 = (B) in (\x1,\y1-1);
It seems like it'd be best if I could do the former option, but many answers on this type of topic online focus on the use of the 'let' command. However, my usage of the let command above is incorrect. I also tried things like
let \p1 =(B) in \coordinate (C) at (\x1,\y1-1);
but this also didn't work. I haven't seen any examples of the let command used in conjunction with \coordinate so not sure what the syntax should be.
So my question is, what is the best way to assign C? I could define it inline when using \draw to draw the line from A to B to C, but then I don't think I'd have access to the C coordinate again without recomputing.
Best Answer
Basic Coordinate Calculations:
You can use the tikz's
calc
library to compute the coordinate for(C)
as follows:The use of the
$
triggers the computation.You can also compute positions between one coordinate to another. For example
($(A)!0.5!(B)$)
represents the amount that is0.5
along the line from(A)
to(B)
.The example below draws a red line from
(C)
to this point which it label the node as(D)
. This point(D)
can then be referred to later, as shown in the case of the brown line. Note that if you don't useshape=coordinate
you would need to use(D.center)
to access the middle of thenode
.References:
As percusse suggested, calculation of
($(B) + (0,-1)$)
can also be done without the use of tikz'scalc
library using theshift
option:Code:
Advanced Coordinate Calculations:
The above method works great if all you are doing is adding/subtracting coordinates. If however you want to apply more general transformations, we need to access the individual
x
andy
coordinates. For this thelet
syntax is useful.For example, to compute the case indicated in the comments where we desire
C
to be at some multiple of thex
andy
coordinates, we can use: