将图例标签与文本对齐

将图例标签与文本对齐

我有这个 MWE。

\documentclass{article}

\usepackage{pgfplots}
\usetikzlibrary{patterns}
\definecolor{nrgray}{HTML}{F0F0F0}

\newcommand{\graphTripleData}[4]{
\begin{tikzpicture}
\begin{axis}[
        legend style={
            at={(1.5,1)}
        },
        legend entries={
            No references,Positive,Negative
        },
        clip bounding box=upper bound,
        hide axis,
        xbar, 
        reverse legend, 
        nodes near coords={\pgfmathfloatifflags{\pgfplotspointmeta}{0}{}{\pgfmathprintnumber{\pgfplotspointmeta}#4}}]

\addplot
[fill=nrgray]
coordinates 
    {(#3,0)};

\addplot
[fill=red]
coordinates 
    {(#2,0)};

\addplot
[fill=green]
coordinates
    {(#1,0)};
\end{axis}
\end{tikzpicture}
}

\begin{document}

\graphTripleData{0}{10}{90}{\%}\\
FAEFA

\end{document}

其输出如下:

平均能量损失

据我所知,图例默认将图例标签与名称中间对齐,但正如所见,这并没有发生,而是与顶部对齐。我该如何强制这种中间对齐?

附言:我一直在读《传奇式主播》,但我并没有用它做任何事情。

答案1

我认为样式的定义xbar legend不太正确:请注意每个图例条目中的第一个条的长度为零。您可以通过在序言中添加以下定义来更正外观:

\pgfplotsset{
/pgfplots/xbar legend/.style={
/pgfplots/legend image code/.code={%
\draw[##1,/tikz/.cd, bar width=3pt,yshift=-0.1em,bar shift=0pt]
plot coordinates {(0.8em, 0cm) (0.6em, 1.7*\pgfplotbarwidth)};},
}
}

\documentclass{article}

\usepackage{pgfplots}
\usetikzlibrary{patterns}
\definecolor{nrgray}{HTML}{F0F0F0}

\pgfplotsset{
/pgfplots/xbar legend/.style={
/pgfplots/legend image code/.code={%
\draw[##1,/tikz/.cd, bar width=3pt,yshift=-0.1em,bar shift=0pt]
plot coordinates {(0.8em, 0cm) (0.6em, 1.7*\pgfplotbarwidth)};},
}
}


\newcommand{\graphTripleData}[4]{
\begin{tikzpicture}
\begin{axis}[
        legend style={
            at={(1.5,1)}
        },
        legend entries={
            No references,Positive,Negative
        },
        clip bounding box=upper bound,
        hide axis,
        xbar, 
        reverse legend, 
        nodes near coords={\pgfmathfloatifflags{\pgfplotspointmeta}{0}{}{\pgfmathprintnumber{\pgfplotspointmeta}#4}}]

\addplot
[fill=nrgray]
coordinates 
    {(#3,0)};

\addplot
[fill=red]
coordinates 
    {(#2,0)};

\addplot
[fill=green]
coordinates
    {(#1,0)};
\end{axis}
\end{tikzpicture}
}

\begin{document}

\graphTripleData{0}{10}{90}{\%}\\
FAEFA

\end{document}

相关内容