建立帶有序數 x 軸的長條圖?

建立帶有序數 x 軸的長條圖?

我正在嘗試創建一個條形圖,其中 x 軸上的值不相關。我目前的程式碼是這樣的:

\documentclass{article}
\beging{document}
\begin{figure}
\centering
     \begin{tikzpicture}
        \begin{axis}[ylabel=Similarity,
                    ybar]
            \addplot table[y=Pref, col sep=comma] {5_Results/evalresults.csv};
            \addplot table[y=Rec, col sep=comma] {5_Results/evalresults.csv};

        \end{axis}
    \end{tikzpicture}
    \caption{A bar chart of user and course similarity}
    \label{evalresultsbar}
\end{figure}
\end{document}

然而,這會產生此圖表。我不只是想刪除沿著 x 軸的值,我還想阻止條形堆疊在一起。

我想要的輸出看起來像Google表格產生的圖表: 在此輸入影像描述

evalresults.csv 的內容

Pref,Rec,label
0.00,14.29,a
0.00,16.67,a
0.00,16.67,a
0.00,20.00,a
0.00,20.00,a
0.00,25.00,a
0.00,33.33,a
0.00,33.33,a
0.00,33.33,a
0.00,50.00,a
0.00,50.00,a
0.00,50.00,a
0.00,50.00,a
0.00,50.00,a
0.00,60.00,a
0.00,60.00,a
0.00,60.00,a
33.33,25.00,a
33.33,25.00,a
33.33,33.33,a
33.33,33.33,a
33.33,60.00,a
33.33,60.00,a
33.33,66.67,a
33.33,75.00,a
33.33,75.00,a
33.33,75.00,a
33.33,80.00,a
33.33,80.00,a
33.33,100.00,a
66.67,75.00,a
66.67,80.00,a
66.67,100.00,a
66.67,100.00,a
66.67,100.00,a
66.67,100.00,a
100.00,100.00,a

答案1

您需要以某種方式指定 x 座標,因此請新增x expr=\coordindex的選項table,如下所示。

我在程式碼中添加了一些註釋

在此輸入影像描述

\documentclass[border=5mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}
\usepackage{pgfplotstable} % for pgfplotstableread, but you can use the filename in the \addplot as you did instead
\pgfplotstableread[col sep=comma]{
Pref,Rec,label
0.00,14.29,a
0.00,16.67,a
0.00,16.67,a
0.00,20.00,a
0.00,20.00,a
0.00,25.00,a
0.00,33.33,a
0.00,33.33,a
0.00,33.33,a
0.00,50.00,a
0.00,50.00,a
0.00,50.00,a
0.00,50.00,a
0.00,50.00,a
0.00,60.00,a
0.00,60.00,a
0.00,60.00,a
33.33,25.00,a
33.33,25.00,a
33.33,33.33,a
33.33,33.33,a
33.33,60.00,a
33.33,60.00,a
33.33,66.67,a
33.33,75.00,a
33.33,75.00,a
33.33,75.00,a
33.33,80.00,a
33.33,80.00,a
33.33,100.00,a
66.67,75.00,a
66.67,80.00,a
66.67,100.00,a
66.67,100.00,a
66.67,100.00,a
66.67,100.00,a
100.00,100.00,a
}\data
\begin{document}    
\begin{tikzpicture}
\begin{axis}[
  ylabel=Similarity,
  ybar,
  % reduce bar width
  bar width=1pt,
  % to remove whitespace below bars
  ymin=0,
  % only want the x-axis on the bottom
  axis x line=bottom,
  % add some horizontal space between bars and axis limits
  enlarge x limits=0.05,
  % don't draw the ticks
  tick style={draw=none},
  % remove x ticks
  xtick=\empty,
  % enable grid
  grid=major,
  % don't draw the vertical lines for the y-axes
  every outer y axis line/.style={draw=none},
  %position legend outside the axis, top right
  legend pos=outer north east,
  % don't draw box around legend
  legend style={draw=none}
]
    \addplot [fill=red!50,draw=none] table[x expr=\coordindex,y=Pref, col sep=comma] {\data};
    \addplot [fill=blue!30,draw=none] table[x expr=\coordindex,y=Rec, col sep=comma] {\data};

   \addlegendentry{Pref}
   \addlegendentry{Rec}

\end{axis}
\end{tikzpicture}
\end{document}

相關內容