# Histogram from single column in datafile

How can read in the following data and display a histogram of the frequency? I also want to add the labels 'WIN' and 'LOSS' (i.e. 0 and 1) and display the count above each bar.

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

\begin{filecontents*}{data.csv}
Period,Subject,Result,Direction
1,1,0,0
2,1,0,0
3,1,1,0
4,1,0,1
5,1,0,0
1,2,1,1
2,2,1,1
3,2,1,1
4,2,0,0
5,2,0,0
1,3,1,0
2,3,1,1
3,3,0,0
4,3,1,1
5,3,0,0
1,4,0,0
2,4,1,1
3,4,0,0
4,4,0,0
5,4,0,0
1,5,0,1
2,5,0,1
3,5,0,1
4,5,1,1
5,5,0,0
\end{filecontents*}

\begin{document}
%Period,Subject,Result,Direction

\begin{tikzpicture}
\begin{axis}[
symbolic x coords={0,1},
xtick=data,
ylabel=Participants,
enlarge x limits=0.40,
]
col sep=comma,
x=Direction,
] {data.csv};
\end{axis}
\end{tikzpicture}

\end{document}


I was able to get this to work when I just had one or two columns in the data.csv file, but it doesn't once I need to select columns from it.

• I'm not sure that I understand what the desired output is. Do you just want two bars, one for the number of rows where Direction=0 and one for the number of rows where Direction=1? – Jake Feb 24 '15 at 10:53
• For this MWE, yes. Just two bars, but I want to label the x-axis 'WIN' and 'LOSS' for 1 and 0. – user2146441 Feb 24 '15 at 11:32

To get the histogram, remove the symbolic x coords and set

hist = {
bins = 2,
data min = 0,
data max = 2
}


in the \addplot options.

To add the labels on the axis, set

xtick = {0,1},
xticklabels = {Loss, Win}


in the axis options.

To get the data labels on top of the bars, set

nodes near coords


in the axis options and

intervals = false,
handler/.style = {ybar}


in the hist options and

bar direction = y,
bar width = 1


in the \addplot options.

\documentclass{article}
\usepackage{filecontents}
\usepackage{pgfplots, pgfplotstable}
\pgfplotsset{compat = 1.11}

\begin{filecontents*}{data.csv}
Period,Subject,Result,Direction
1,1,0,0
2,1,0,0
3,1,1,0
4,1,0,1
5,1,0,0
1,2,1,1
2,2,1,1
3,2,1,1
4,2,0,0
5,2,0,0
1,3,1,0
2,3,1,1
3,3,0,0
4,3,1,1
5,3,0,0
1,4,0,0
2,4,1,1
3,4,0,0
4,4,0,0
5,4,0,0
1,5,0,1
2,5,0,1
3,5,0,1
4,5,1,1
5,5,0,0
\end{filecontents*}

\begin{document}
\begin{tikzpicture}
\begin{axis}[
ylabel = Participants,
enlarge x limits = 1,
xtick = {0,1},
xticklabels = {Loss, Win},
ymin = 0,
nodes near coords,
xtick pos = left
]
fill=gray,
hist = {
bins = 2,
data min = 0,
data max = 2,
intervals = false,
handler/.style = {ybar},
},
bar direction = y,
bar width = 1
] table [
col sep = comma,
y = Direction,
] {data.csv};
\end{axis}
\end{tikzpicture}

\end{document}