2

In the legend of a pgfplot, the text is on the right of the image. Is it possible to move the text to the left of the image for a single entry?

For example, the following LaTeX code will produce a legend that reads

[░░] Bad   [▒▒]   [██] Good

Instead, I would like to move "Bad" to the left of the legend image and get

Bad [░░]   [▒▒]   [██] Good

Is there a way to accomplish this with pgfplots?

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots, pgfplotstable}

\pgfplotsset{compat=1.17}

\begin{document}

\pgfplotstableread[col sep=&]{
Q & A & B & C
Q1 & 0 & 1 & 3
Q2 & 2 & 1 & 1
}{\answers}

\begin{tikzpicture}
\begin{axis}[
    legend columns=-1,
    legend to name=leg1,
    xbar stacked,
    y=0.8cm, y dir=reverse, xmin=0, xmax=4,
    ytick=data, yticklabels from table={\answers}{Q},
]

    \addplot [fill=red] table [x=A, y expr=\coordindex] {\answers};
    \addplot [fill=yellow] table [x=B, y expr=\coordindex] {\answers};
    \addplot [fill=green] table [x=C, y expr=\coordindex] {\answers};
    
    \legend{Bad, { },Good}

\end{axis}
\end{tikzpicture}

\ref{leg1}

\end{document}

1 Answer 1

1

One way is to add an extra legend entry with the word Bad as image and an empty description, then the red and yellow plot as normal legend entries without description, and then the green plot with the word Good as description.

This creates a bit of space between the first legend entry (the word Bad) and the second entry (the red rectangle), so you can adjust that with some negative kerning.

The code for adding a text 'image' in the legend is taken from Add custom entry into legend in pgfplot.

MWE:

\documentclass{article}
\usepackage{tikz}
\usepackage{pgfplots, pgfplotstable}

\pgfplotsset{compat=1.16}
\pgfplotsset{
    legend image with text/.style={
        legend image code/.code={%
            \node[anchor=center] at (0.3cm,0cm) {#1};
        }
    },
}
\begin{document}

\pgfplotstableread[col sep=&]{
Q & A & B & C
Q1 & 0 & 1 & 3
Q2 & 2 & 1 & 1
}{\answers}

\begin{tikzpicture}
\begin{axis}[
    legend columns=-1,
    legend to name=leg1,
    xbar stacked,
    y=0.8cm, y dir=reverse, xmin=0, xmax=4,
    ytick=data, yticklabels from table={\answers}{Q},
]
    \addlegendimage{legend image with text=Bad\kern-3pt}
    \addlegendentry{{}}
    \addplot [fill=red] table [x=A, y expr=\coordindex] {\answers};
    \addlegendentry{{}}
    \addplot [fill=yellow] table [x=B, y expr=\coordindex] {\answers};
    \addlegendentry{{}}
    \addplot [fill=green] table [x=C, y expr=\coordindex] {\answers};
    \addlegendentry{Good}
    
    %\legend{Bad, { },Good}

\end{axis}
\end{tikzpicture}

\ref{leg1}

\end{document}

Result:

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .