数据文件中单列的直方图

数据文件中单列的直方图

如何读取以下数据并显示频率直方图?我还想添加标签“WIN”和“LOSS”(即 0 和 1)并在每个条形上方显示计数。

\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,
                ]
\addplot[ybar,fill=gray] table [        
col sep=comma,
x=Direction,
    ] {data.csv};
                \end{axis}
                \end{tikzpicture}

\end{document}

当 data.csv 文件中只有一两列时,我可以让它工作,但是当我需要从中选择列时,它却无法工作。

答案1

要获取直方图,请删除symbolic x coords并设置

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

\addplot选项中。

要在轴上添加标签,请设置

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

axis选项中。

要获取条形图顶部的数据标签,请设置

nodes near coords

axis选项和

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

hist选项和

bar direction = y,
bar width = 1

\addplot选项中。

\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
]
\addplot[
    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}

相关内容