7

Is there a (simple) way to extract polar coordinates in Tikz?

Motivation: I define two points (a) and (b) as intersection of a line and a circle (center at the origin) and then I want to an arc between these two points along my circle. I need the polar coordinates of (a) and (b) for that.

I have seen in the TikZ documentation that there is \pgfextractx{<dimension>}{<point>} to extract the x-coordinate, and a similar function for the y-coordinate as well, but could not find something for polar coordinates.

2 Answers 2

11

You can define your own macro analogous to \pgfgetlastxy to extract the last cartesian coordinates, convert them into polar coordinates and store the resulting values in macros:

(Thanks to @John Kormylo the macro below has gradually become the short and crisp piece of code it is now. It only needs the tikz package without any additional libraries.)

\documentclass[border=1mm, tikz]{standalone}

\newcommand{\pgfgetlastpolar}[2]{
    \pgfgetlastxy{\tempx}{\tempy}
    \pgfmathsetmacro{#1}{atan2(\tempy,\tempx)}
    \pgfmathsetlengthmacro{#2}{veclen(\tempx,\tempy)}
}

\begin{document}
\begin{tikzpicture}

\node[draw, circle] at (1,1) {};

% use analogous to `\pgfgetlastxy{\myx}{\myy}´ 
\pgfgetlastpolar{\mytheta}{\myrho}

\node[draw, rectangle] at (\mytheta:\myrho) {};

\end{tikzpicture}
\end{document}
6
  • 4
    Replaced atan by atan2 to correctly handle negative cartesian coordinates. Commented Dec 10, 2021 at 11:39
  • I would have gone with \pgfmathsetlengthmacro{#2}{sqrt(\tempx*\tempx+\tempy*\tempy)}. Never use ^ while computing if you can avoid it. Commented Dec 10, 2021 at 16:18
  • @JohnKormylo Thanks. Why, though? Does computing it take longer? I also found, that you very quickly will get a "dimension too large" error (idependently from using ^). Commented Dec 10, 2021 at 16:20
  • 1
    Many times a^b is computed as exp(b*log(a)). Pgfmath is now smart enough to not do that with integers, but why take risks? Also a*x^2+b*x+c should be (a*x+b)*x+c (faster and more accurate). Commented Dec 10, 2021 at 16:26
  • 1
    BTW, you really should use \pgfmathsetmacro instead of \pgfmathsetlengthmacro for the angle. Even if adding pt doesn't hurt, it doesn`t help either. Commented Dec 13, 2021 at 15:41
6

It is really not easy to understand what you want without a minimal example code defining your circle, points, ... and a picture of the desired result.

Here is a guess:

\documentclass[tikz, border=1cm]{standalone}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}[thick]
\coordinate (a) at (20:2);
\coordinate (b) at (100:2);
\draw (0,0) circle[radius=2];
\draw[teal] (a) -- (b);
\draw[red] let \p1=(a), \p2=(b) in (\p1)  arc[radius=veclen(\p1), start angle={atan2(\y1,\x1)}, end angle={atan2(\y2,\x2)}];
\end{tikzpicture}
\end{document}

Circle with chord and arc

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .