Tikz 矩阵节点上的额外左侧空间

Tikz 矩阵节点上的额外左侧空间

我使用以下自制的颜色图例来绘制 Tikz 图形(代码在最后给出):

在此处输入图片描述

但是当我尝试水平打印两个彩色矩形时,左侧会出现一个多余的空格(见下图中的绿色箭头,仅用于解释目的),代码在最后给出:

在此处输入图片描述

有没有办法获得所需的输出(第二个图)而左边没有多余的空间?

代码:

\documentclass[tikz, border=2mm]{standalone}

\begin{document}
    
        \begin{tikzpicture}[]
        
        \path ([xshift=0.07cm,yshift=0cm]current bounding box.north west)%
        node[matrix,anchor=north west,cells={nodes={font=\sffamily,anchor=west}},
        draw,thick,inner sep=1ex]{%
            \path (0,0); \node {\bfseries Legend :}; & \\
            \filldraw[blue] (0,0) rectangle (0.5,0.5)  ; & \node[above, pos=0.1]{main script};\\
            \filldraw[red] (0,0) rectangle (0.5,0.5)  ; & \node[above, pos=0.1]{functions};\\
        };%
    \end{tikzpicture}

    \begin{tikzpicture}[]

\path ([xshift=0.07cm,yshift=0cm]current bounding box.north west)%
node[matrix,anchor=north west,cells={nodes={font=\sffamily,anchor=west}},
draw,thick,inner sep=1ex]{%
    \path (0,0); \node {\bfseries Legend :}; & \\
    \filldraw[blue] (0,0) rectangle (0.5,0.5)  ; & \node[above, pos=0.1]{main script};\\
    \filldraw[red] (0,0) rectangle (0.5,0.5)  ; & \node[above, pos=0.1,]{functions};\\
    \filldraw[gray] (0,0) rectangle (0.5,0.5); \node[above]{\hspace{3.5em} /}; \filldraw[yellow] (0.85,0) rectangle (1.35,0.5); & \node[above, pos=0.1]{other};\\
};%
        \end{tikzpicture}

\end{document}

答案1

导致\hspace了偏移。请将/作为节点放置:

\filldraw[gray] (0,0) rectangle (0.5,0.5); \node at (.42,.25){/}; \filldraw[yellow] (0.85,0) rectangle (1.35,0.5); & \node[above, pos=0.1]{other};\\

在此处输入图片描述

答案2

没有TiKZ

\documentclass{article}

\usepackage{xcolor}

\begin{document}
        
\fbox{\sffamily\begin{tabular}{lc}
\multicolumn{2}{l}{\bfseries Legend:}\\[2mm]
\textcolor{blue}{\rule{5mm}{5mm}} & \raisebox{1.5mm}{main script}\\
\textcolor{red}{\rule{5mm}{5mm}} & \raisebox{1.5mm}{functions}\\
\textcolor{gray}{\rule{5mm}{5mm}}\raisebox{1.5mm}{/}\textcolor{yellow}{\rule{5mm}{5mm}} & \raisebox{1.5mm}{other}\\
\end{tabular}}

\end{document}

在此处输入图片描述

相关内容