[Tex/LaTex] Add label to bars in bar chart

labelspgfplots

I am trying to get labels over the bars in my bar chart.

I found \node [above] at (axis cs: 1, 810) {$Q1$};, but this one centers itself in the middle between two bars. I want the value from the y-axis to be floating over the top of the bar (or maybe inside it)

my MWE looks like this, its not very expressive without labels. any suggestions?

  \documentclass{article}
\usepackage{pgfplots}

\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}
    \begin{axis}[
        ybar,
        width  = 12cm,
        height = 5cm,
        bar width=20pt,
        ylabel={number of participants},
        symbolic x coords={High School, Bachelor degree, Master degree, Ph.D or similar},
        xtick = data,
    ]
    \addplot[fill=blue] coordinates {(High School, 1) (Bachelor degree, 2) (Master degree, 3) (Ph.D or similar, 4)};
     \addplot[fill=red] coordinates {(High School, 3) (Bachelor degree, 2) (Master degree, 8) (Ph.D or similar, 4)};
      \legend{Native speaker, Non-native speaker}
    \end{axis}
\end{tikzpicture}
\caption{Participants: Level of education}
\label{participantsLanguageOverviewNonNative}
\end{figure}
\end{document}

Best Answer

The nodes near coords key does exactly this, so add that to the axis options and you're almost done. You will also want to stretch the axis a little, as there is not enough room for the labels as it is now, so add enlarge y limits={value=0.2,upper} as well. I would also set ymin=0. Finally, move the legend with legend pos=north west, so that it doesn't cover up the bars.

If you want the labels inside the bars, add nodes near coords align=below, in which case you don't need the enlarge y limits.

enter image description here

\documentclass{article}
\usepackage{pgfplots}

\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}
    \begin{axis}[
        ybar,
        ymin=0,
        width=12cm,
        height=5cm,
        bar width=20pt,
        ylabel={number of participants},
        nodes near coords,
 %      nodes near coords align=below, % places labels inside bars
        symbolic x coords={High School, Bachelor degree, Master degree, Ph.D or similar},
        xtick = data,
        enlarge y limits={value=0.2,upper},
        legend pos=north west
    ]
    \addplot[fill=blue] coordinates {(High School, 1) (Bachelor degree, 2) (Master degree, 3) (Ph.D or similar, 4)};
     \addplot[fill=red] coordinates {(High School, 3) (Bachelor degree, 2) (Master degree, 8) (Ph.D or similar, 4)};
      \legend{Native speaker, Non-native speaker}
    \end{axis}
\end{tikzpicture}
\caption{Participants: Level of education}
\label{participantsLanguageOverviewNonNative}
\end{figure}
\end{document}