# Patterned legend in caption

This is a follow-up question of: latex - colorbox in caption as legend - how to center or alternative solution?

For convenient sake, I copy the MWE:

\documentclass{article}
\usepackage{graphicx}
\usepackage{xcolor}

\DeclareRobustCommand{\legendsquare}[1]{%
\textcolor{#1}{\rule{1ex}{1ex}}%
}
\begin{document}
\begin{figure}[hbp]
\centering
\includegraphics[width=.4\textwidth]{example-image}
\caption{Pattern of participants \legendsquare{green}~X,
\legendsquare{orange}~Y,
\legendsquare{black}~Z after}
\label{fig:cha_HAC_RunningTime}
\end{figure}
\end{document}


The colored legend is now indicated in the caption. The boxes are filled with green, orange and black colors.

Question: How do you put some pattern in the colored box, e.g. a diagnal hatch pattern, dotted pattern etc.?

You could replace your command with TikZ. If you want to keep the command definition simple, the coloring commands get slightly more complicated.

You could add draw to the squares with patterns to show the square aspect.

## Code

\documentclass{article}
\usepackage{graphicx}
\usepackage{tikz}

\usetikzlibrary{patterns}

\DeclareRobustCommand{\legendsquare}[1]{%
\tikz[baseline=(a.south)]{\node[#1, inner sep=.8ex, outer sep=0] (a) {};}%
}

\begin{document}
\begin{figure}[!htb]
\centering
\includegraphics[width=.4\textwidth]{example-image}
\caption{Pattern of participants \legendsquare{fill=green}~X,
\legendsquare{pattern=north west lines}~J,
\legendsquare{pattern=dots}~W,
\legendsquare{fill=orange}~Y,
\legendsquare{fill=black}~Z after}
\label{fig:cha_HAC_RunningTime}
\end{figure}
\end{document}