[Tex/LaTex] Using node shapes or self made tikzpicture as image in legend

legendnodespgfplotstikz-pgf

I am using the solutions of

Using a pgfplots-style legend in a plain-old tikzpicture

and

Legend in tikzpicture

to create a legend in a tikzpicture.

In this legend I need a cylinder as image. I know that a node can be shaped as a cylinder. But I don't now how I can use this to create a legend image.

\begin{tikzpicture}

% node shaped as cylinder
\node[shape=cylinder](c) at (0,0){};

% cylinder drawn myself
\draw(3,3)--(4,3);
\draw(3,4)--(4,4);
\draw(3,2.5) ellipse (0.1 and 0.5);
\draw(4,2.5) ellipse (0.1 and 0.5);

\begin{customlegend}[legend cell align=left,
legend entries={ cylinder},
legend style={at={(6,3)},font=\footnotesize}]
\addlegendimage{ ??????? }
\end{customlegend}

\end{tikzpicture}

Best Answer

You can set the code that's used to draw the legend image using legend image code/.code={ ...}:

\documentclass[a4paper,11pt]{article}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}

\usepackage{pgfplots}

% Code from Christian Feuersänger
% http://tex.stackexchange.com/questions/54794/using-a-pgfplots-style-legend-in-a-plain-old-tikzpicture#54834

% argument #1: any options
\newenvironment{customlegend}[1][]{%
    \begingroup
    % inits/clears the lists (which might be populated from previous
    % axes):
    \csname pgfplots@init@cleared@structures\endcsname
    \pgfplotsset{#1}%
}{%
    % draws the legend:
    \csname pgfplots@createlegend\endcsname
    \endgroup
}%

% makes \addlegendimage available (typically only available within an
% axis environment):
\def\addlegendimage{\csname pgfplots@addlegendimage\endcsname}

%%--------------------------------

% definition to insert numbers
\pgfkeys{/pgfplots/number in legend/.style={%
        /pgfplots/legend image code/.code={%
            \node at (0.295,-0.0225){#1};
        },%
    },
}

\begin{document}
\begin{tikzpicture}

% node shaped as cylinder
\node[shape=cylinder](c) at (0,0){};

% cylinder drawn myself
\draw(3,3)--(4,3);
\draw(3,4)--(4,4);
\draw(3,4) arc [x radius=0.1, y radius=0.5, start angle=90, end angle=270];
\draw(4,3.5) ellipse (0.1 and 0.5);

\begin{customlegend}[legend cell align=left,
legend entries={ cylinder},
legend style={at={(6,3)},font=\footnotesize}]
\addlegendimage{legend image code/.code={\node [draw, cylinder, minimum size=1em] {};}}
\end{customlegend}

\end{tikzpicture}


\end{document}