2 個具有共同 x 軸的直方圖未對齊

2 個具有共同 x 軸的直方圖未對齊

我必須遵循乳膠代碼:

\usepackage{tikz}
\usepackage{pgfopts}
\usepackage{pgfplotstable}
\begin{document}
\begin{tikzpicture}[scale=1]
\begin{axis}[minor tick num=1,
            scale only axis,
            height=5cm,
            width=\textwidth*0.8,
            xlabel=\textnumero contestants,
            ylabel style={overlay},
                yticklabel style={overlay},
            xticklabel style={overlay},
            ylabel=,
            ybar,
            ymin=0,
            legend style={at={(0, 1)},anchor=west},
            legend entries={\textnumero matches, \textnumero rounds}]
\addplot [draw opacity=0,fill=yellow!50] table [x index=0, y index=1] {charts/merge_no_matches_rounds.csv};
\addplot [draw opacity=0,fill=green] table [x index=0, y index=2] {charts/merge_no_matches_rounds.csv};
\end{axis}
\end{tikzpicture}
\end{document}

這是結果: 結果

資料檔如下所示:

2   1   1
4   4   3
6   9   6
8   11  6
10  17  9
12  21  9
14  23  9
. . .
92  181 18
94  185 18
96  189 18
98  191 18
100 193 18

黃色區域看起來不錯,但綠色區域有一個奇怪的偏移。我該如何解決這個問題?

答案1

您不應該在這裡使用直方圖。如果黃色資料的一個值低於相應的綠色值,則您的繪圖想法不再實用。您應該使用真實的條形或真實的堆疊,而不是混合。 (實際上,簡單的曲線是最好的)

不過,我還是為你提供了一個解決方案:

% arara: pdflatex

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.11}
\usepgfplotslibrary{fillbetween}
\usepackage{textcomp}
\usepackage{filecontents}
\begin{filecontents*}{charts/merge_no_matches_rounds.csv}
    2   1   1
    4   4   3
    6   9   6
    8   11  6
    10  17  9
    12  21  9
    14  23  9
    92  181 18
    94  185 18
    96  189 18
    98  191 18
    100 193 18
\end{filecontents*}
\begin{document}
    \begin{figure}
        \centering
    \begin{tikzpicture}
    \begin{axis}[%
    ,minor tick num=1
    ,scale only axis
    ,height=5cm
    ,width=\textwidth*0.8
    ,xlabel=\textnumero{} contestants
    ,yticklabel style={overlay}
    ,xticklabel style={overlay}
    ,ymin=0
    ,legend cell align=left
    ,legend style={at={(0, 1)},anchor=west}]
    \addplot [draw opacity=0,name path=f,area legend,fill=yellow!50] table [x index=0, y index=1] {charts/merge_no_matches_rounds.csv};
    \addplot [draw opacity=0,name path=g,area legend,fill=green] table [x index=0, y index=2] {charts/merge_no_matches_rounds.csv};
    \path[name path=axis] (axis cs:0,0.2) -- (axis cs:100,0.2);
    \addplot [draw opacity=0,color=yellow!50,fill=yellow!50]
    fill between[of=f and axis];
    \addlegendentry{\textnumero{} matches}
    \addplot [draw opacity=0,color=green,fill=green]
    fill between[of=g and axis];
    \addlegendentry{\textnumero{} rounds}
    \end{axis}
    \end{tikzpicture}
    \end{figure}    
\end{document}

在此輸入影像描述

相關內容