TransWikia.com

How to correctly draw this picture in TikZ?

TeX - LaTeX Asked on December 20, 2020

This is the picture I want to make:
ideal result

This is generated by the following extremely ugly code:

documentclass[tikz]{standalone}

usetikzlibrary{decorations.markings}
usetikzlibrary{hobby}

definecolor{col1}{RGB}{127,127,127}
definecolor{col2}{RGB}{240,240,240}

begin{document}

begin{tikzpicture}[use Hobby shortcut]
    clip (0,0) rectangle (1,1);
    path[yshift=10,
    postaction={
        decorate,
        decoration={
            markings,
            mark=between positions 0 and pgfdecoratedpathlength step .01cm with {
                pgfmathsetmacromyval{multiply(divide(
                    pgfkeysvalueof{/pgf/decoration/mark info/distance from start}, pgfdecoratedpathlength),100)};
                pgfsetfillcolor{col2!myval!col1};
                pgfpathcircle{pgfpointorigin}{1.5};
                pgfusepath{fill};}
    }}] 
    (.075,.2)..([closed].2,.4)..(.8,0)..(.925,.2)..(.8,.4)..(.2,0);
    fill[col1] (.075,.55) circle (0.052cm);
end{tikzpicture}

end{document}

This code cannot be compiled because there would be many errors like this one:

Dimension too large. (...2,.4)..(.8,0)..(.925,.2)..(.8,.4)..(.2,0); ...)

However I’m able to get the result pdf and hence the picture above.

My question is this: how to draw this picture correctly? Thanks in advance for any coming suggestions ~

One Answer

With pgfplots you can use point meta to change the color along a graph.

documentclass[tikz,border=3mm]{standalone}
usepackage{pgfplots}
pgfplotsset{compat=1.17}
begin{document}
begin{tikzpicture}
begin{axis}[hide axis,width=8cm,height=4cm,clip=false] 
addplot[domain=0:360,samples=720,line cap=round,        
colormap={}{ 
            color(0cm)=(gray!10);
            color(16cm)=(gray);
        },
        line width=5mm, variable=t,point meta=t,mesh]
        ({-cos(t)},{-sin(2*t)});
end{axis}
end{tikzpicture}
end{document}

enter image description here

In order to have the proper bounding box, you can store the line width in a macro.

documentclass[tikz]{standalone}
usepackage{pgfplots}
pgfplotsset{compat=1.17}
begin{document}
begin{tikzpicture}
begin{axis}[hide axis,width=8cm,height=4cm,clip=false]
defmylw{5mm} %<- line width 
addplot[domain=0:360,samples=720,line cap=round,        
colormap={}{ 
            color(0cm)=(gray!10);
            color(16cm)=(gray);
        },
        line width=mylw, variable=t,point meta=t,mesh]
        ({-cos(t)},{-sin(2*t)});
% add points to have an appropriat bounding box     
path ([xshift=-mylw/2,yshift=-mylw/2]-1,-1)
 ([xshift=mylw/2,yshift=mylw/2]1,1);      
end{axis}
end{tikzpicture}
end{document}

Correct answer by user227987 on December 20, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP