Creating a smooth gradient between two colors on an edge in TikZ
Update: fixed gradient angle
Here is an idea. You can "connect" two nodes using another node, with option sloped
, and minimum width equal to the distance between the nodes to connect. The shape of the "connecting" node is by default a rectangle which you can fill with a gradient. But you can even try more exotic node shapes for the "connection".
The following code implements a macro which simplifies the syntax:
% Requires \usetikzlibrary{calc}
\def\connect#1#2#3{%
% #1: starting node
% #2: ending node
% #3: attributes for the shape connecting nodes
\path let
\p1 = ($(#2)-(#1)$),
\n1 = {veclen(\p1)},
\n2 = {atan2(\x1,\y1)} % <- Update
in
(#1) -- (#2) node[#3, midway, sloped, shading angle=\n2+90, minimum width=\n1, inner sep=0pt, #3] {};
}
You can use this macro as in: \connect{A}{B}{options}
, being A
and B
the coordinates to connect and options
the ones to be used for the node which fakes the connection. Here you can specify the gradient, as for example:
\begin{tikzpicture}
\foreach \A/\B in {{0,0}/{2,1}, {3,0}/{1,1}} {
\fill [red] (\A) circle(2pt);
\fill [blue] (\B) circle(2pt);
\connect{\A}{\B}{bottom color=blue, top color=red, minimum height=1pt}
}
\end{tikzpicture}
Which produces:
Note that minimum height
specifies in this case the "connection" width.
As said, you can use more exotic shapes as connectors, as for example ellipses:
% ...
\connect{\A}{\B}{bottom color=blue, top color=red, minimum height=1pt, ellipse}
Adding onto JLDiaz's answer--and sorry to wake up such an old post!
I had some trouble with the other solution, I think due to the atan2 typo. According to the Tikz/PGF manual, the argument is in y, x order--I assume to mimic the mathematical atan(y/x). This is why in the given example the +90 is needed to fix the angle in the original code. I have also flipped the top / bottom color order. I will leave my answer below.
I have added labeled nodes and used arrows instead of the default edge shape, but otherwise it is the same as JLDiaz.
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc, shapes.arrows}
\def\connect#1#2#3{%
% #1: starting node
% #2: ending node
% #3: attributes for the shape connecting nodes
\path let
\p1 = ($(#2)-(#1)$),
\n1 = {veclen(\p1)-0.6cm},
\n2 = {atan2(\y1,\x1)} % <- Update
in
(#1) -- (#2) node[#3, midway, rotate = \n2, shading angle = \n2+90, minimum height=\n1, minimum width=1pt, inner sep=1pt] {};
}
\begin{document}
\vspace{1cm}
\begin{tikzpicture}
\foreach \A/\B in {{0,0}/{4,2}, {6,0}/{2,2}, {8,0}/{8,2}, {10,2}/{10,0}} {
\connect{\A}{\B}{single arrow, top color=orange, bottom color=blue};
\fill [gray!50] (\A) circle (0.3cm);
\draw (\A) circle (0.3cm) node {$A$};
\fill [gray!50] (\B) circle (0.3cm);
\draw (\B) circle (0.3cm) node {$B$};
}
\end{tikzpicture}
\end{document}
And this produces the following image: