10

This is my code.

\documentclass{article}

\usepackage{tikz}

\begin{document}
    \def\magnet at (#1,#2,#3){\draw [rotate=#3] (#1,#2) ellipse (0.8 and 0.4)
        node at (#1-0.4,#2) {N}
        node at (#1+0.4,#2) {S};}

    \begin{figure}
        \centering
        \begin{tikzpicture}
        \magnet at (1,0,30);
        \magnet at (3,0,30);
        \magnet at (5,0,30);
        \end{tikzpicture}
    \end{figure}
\end{document}

Why are the ellipses not horizontally aligned even when their centers have same y-value?

enter image description here

6
  • They are aligned: add \draw (0,0) -- (30:7cm);.
    – percusse
    Commented Aug 22, 2015 at 7:34
  • @percusse, nice. But I guess that the OP wants output as 3 rotated ellipses side by side on the same row.
    – Sigur
    Commented Aug 22, 2015 at 7:42
  • @Sigur Yes, that is exactly what I want. Commented Aug 22, 2015 at 7:43
  • 2
    Ah OK. My bad. Then one possibility is \draw[rotate around={#3:(#1,#2)}].... . In your code (#1,#2) also picks up the rotation with respect to origin. You can alternatively write \coordinate(temp) at (#1,#2); before this line and use \draw[rotate=30] (temp) ellipse .... and adjust node text with respect to (temp)
    – percusse
    Commented Aug 22, 2015 at 7:50
  • @percusse Your suggestion works. Can you add it as an answer? I used \draw[rotate around={#3:(#1,#2)}].... Commented Aug 22, 2015 at 7:54

2 Answers 2

12

A solution via pic, a feature of TikZ 3.0:

\documentclass{article}

\usepackage{tikz}

\tikzset{
  magnet/.pic={
    \draw
      ellipse (0.8 and 0.4)
      node at (-0.4, 0) {N}
      node at (0.4, 0) {S}
    ;
  },
}

\begin{document}

  \begin{figure}
    \centering
    \begin{tikzpicture}
      \path
         (1, 0) pic[rotate=30]{magnet}
         (3, 0) pic[rotate=30]{magnet}
         (5, 0) pic[rotate=30]{magnet}
      ;
    \end{tikzpicture}
  \end{figure}
\end{document}

Result

0

By using \tikz in the definition, and dropping the ; at the end, the result is three ellipses next to each other. Still learning tikz myself.

\documentclass{article}

\usepackage{tikz}

\begin{document}

\def\magnet at (#1,#2,#3){\tikz \draw [rotate=#3] (#1,#2) ellipse (0.8 and 0.4)
    node at (#1-0.4,#2) {N}
    node at (#1+0.4,#2) {S}}

\begin{figure}
    \centering
    \magnet at (1,0,30);
    \magnet at (3,0,30);
    \magnet at (5,0,30);              
\end{figure}
\end{document}

You must log in to answer this question.

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