3

I was trying to build a stacked bar graph which displays the labels of the columns title not in a legend, but directly near the bar itself. So far, I came up with the following:

\documentclass[12pt]{amsart}
\usepackage{pgfplots,pgfplotstable}
\pgfplotstableread{
Column  abc def ghi
col1    32  2   35
col2    34  54  2
}\MyName
\begin{document}
\begin{tikzpicture}
\begin{axis}[ybar=0pt,
ybar stacked,
bar shift=0pt,
xticklabels from table={\MyName}{Column},
xtick=data,
nodes near coords=\col
]
\pgfplotstableforeachcolumn\MyName\as\col{%
    \ifnum\pgfplotstablecol=0 
    \else
    \edef\tmp{%
        \noexpand\addplot table [x expr=\noexpand\coordindex,y=\col] {\noexpand\MyName};
    }%
    \tmp
    \fi
}
\end{axis}
\end{tikzpicture}
\end{document}

Unfortunately, in the resulting diagram all labels are set to the last column title, to "ghi", instead of "abc", "def" and "ghi" respectively. Does anyone have a good idea? Thanks in advance!

  • Welcome to TeX.SX! You can have a look at our starter guide to familiarize yourself further with our format. – Andrew Swann Feb 25 '14 at 8:36
0

One of the problems is that you set nodes near coords=\col outside the scope of the loop where \col is set. This happens to interfere with the ticks as well. What you need to do is set the value used by nodes near coords inside the loop. The key to this is to assign point meta. Usually this expects something that gives a number, but there is (a slightly convoluted) way to provide text via TeX code, by specifying

point meta={TeX code symbolic={\edef\pgfplotspointmeta{\col}}}

The TeX code symbolic option takes some code that should define the command \pgfplotspointmeta so it typesets the desired label. In your case, inside the loop \col already does what you want.

Sample output

\documentclass[12pt]{amsart}

\usepackage{pgfplotstable}
\pgfplotsset{compat=1.9}

\pgfplotstableread{
Column  abc def ghi
col1    32  2   35
col2    34  54  2
}\MyName

\begin{document}

\begin{tikzpicture}
\begin{axis}[ybar=0pt,
ybar stacked,
nodes near coords,
bar shift=0pt,
xticklabels from table={\MyName}{Column},
xtick=data,
ymin=0
]
\pgfplotstableforeachcolumn\MyName\as\col{%
    \ifnum\pgfplotstablecol=0 
    \else
    \addplot+[point meta={TeX code symbolic={\edef\pgfplotspointmeta{\col}}}] table [x expr=\coordindex,y=\col] {\MyName};
    \fi}
\end{axis}
\end{tikzpicture}

\end{document}

Note that setting ymin=0 is necessary to get reasonable placing of the lowest node label. I used \addplot+ instead of \addplot so that previous options are not overridden.

  • That's fantastic, I've been trying to do that for longer than I want to admit. Thank you very much, Andrew! – user3086366 Feb 25 '14 at 12:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.