无符号坐标

无符号坐标

所以我有这个“分组”条形图,如下所示。

在此处输入图片描述

我想要x-ticks被标记

-2, -1, 0, 1, 2, 3, 4, 5

我该如何实现这一点?目前只显示 -2 和 -1

\documentclass[12pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{width=6.6cm,compat=1.7}
\begin{document}
\begin{tikzpicture}

\begin{axis}[
    ybar,
    enlargelimits=0.15,
    ylabel={\# Number of students}, % the ylabel must precede a # symbol.
    xlabel={Difference},
    symbolic x coords={mTwo, mOne, Zero, pOne, pTwo, pThree, pFour, pFive}, % these are the specification of coordinates on the x-axis.
    xtick=data,
     nodes near coords, % this command is used to mention the y-axis points on the top of the particular bar.
    nodes near coords align={vertical},
    xticklabels = {$-2$,$-1$,$0$,$1$,$2$,$3$,$4$,$5$}
    ]
\addplot coordinates { (mTwo,2) (mOne,1) };
\addplot coordinates { (Zero,5) };
\addplot coordinates { (pOne,3) (pTwo,15) (pThree,10) (pFour,5) (pFive,1) };

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

答案1

正如 @rbrignall 所说,您只从中的xtick第一个获取数据,这只会产生两个刻度,因此会产生两个刻度标签。我不太清楚为什么这里需要符号坐标(请参阅下面的更简单的代码,无需它们),但为了查看所有刻度,您可以传递值。由于我们还需要将其输入到,我建议将其存储在 PGF 键中,例如,并使用— 在应用中从此值设置 和\addplotaxisxtickmTwo, mOne, Zero, pOne, pTwo, pThree, pFour, pFivesymbolic x coords/pgfplots/my coords/pgfplots/symbolic x coords/pgfplots/xtick\pgfkeysvalueof{/pgfplots/my coords}DRY 原则

我还设置了bar shift=0pt,否则\addplot由于使用,每个新的都会水平移动坐标系ybar,这可能不是你想要的。

\documentclass[tikz, border=2mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}

\begin{document}
\begin{tikzpicture}

\begin{axis}[
    ybar, bar width=0.6cm,
    enlargelimits=0.15,
    ylabel={\# Number of students},
    xlabel={Difference},
    % This is used to avoid repeating the list of symbolic coordinates
    my coords/.initial={mTwo, mOne, Zero, pOne, pTwo, pThree, pFour, pFive},
    symbolic x coords/.expanded={\pgfkeysvalueof{/pgfplots/my coords}},
    xtick/.expanded={\pgfkeysvalueof{/pgfplots/my coords}},
    nodes near coords,
    nodes near coords align={vertical},
    xticklabels = {$-2$, $-1$, $0$, $1$, $2$, $3$, $4$, $5$},
    bar shift=0pt,
    ]
\addplot coordinates { (mTwo,2) (mOne,1) };
\addplot coordinates { (Zero,5) };
\addplot coordinates { (pOne,3) (pTwo,15) (pThree,10) (pFour,5) (pFive,1) };
\end{axis}

\end{tikzpicture}
\end{document}

在此处输入图片描述

PS:pgfplots compat1.7级是老的,我将其提升至 1.16。

无符号坐标

可以用更简单的方式绘制相同的图,不需要符号坐标:

\documentclass[tikz, border=2mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}

\begin{document}
\begin{tikzpicture}

\begin{axis}[
    ybar, bar width=0.6cm,
    enlargelimits=0.15,
    ylabel={\# Number of students},
    xlabel={Difference},
    xtick={-2,...,5},
    nodes near coords,
    nodes near coords align={vertical},
    bar shift=0pt,
    ]
\addplot coordinates { (-2,2) (-1,1) };
\addplot coordinates { (0,5) };
\addplot coordinates { (1,3) (2,15) (3,10) (4,5) (5,1) };
\end{axis}

\end{tikzpicture}
\end{document}

(与第一个例子的输出相同)。

相关内容