我有一份文档,其中需要这样的条形图:
我用作pgfplots
:
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis} [ybar,
ymin=0,
xtick=data,
xtick pos=left,
xticklabel interval boundaries,
nodes near coords,
nodes near coords style = {anchor=south west,
align=center},
symbolic x coords={A,B,C,D,E,F,G,H},
]
\addplot [ybar interval] coordinates
{(A, 5) (B, 7)
(C, 9) (D, 15)
(E, 8) (F, 20)
(G, 16) (H, 13)
};
\end{axis}
\end{tikzpicture}
\end{document}
但该列H
消失了:
我在某处(我不记得在哪里)读到过一种解决方法,即添加一个值为 0 的列,所以我这样做了。问题是,列I
不应该存在于结果图表中,但它也有自己的标签:
有没有办法删除它(保留其他列)?或者有没有更好的方法显示pgfplots
所有列?
答案1
如果您添加\pgfplotsset{compat=1.7}
或更高版本,则可以设置bar width=1
,并且条形的宽度将为 1(以轴为单位)。但这不适用于符号坐标,因此您需要数字坐标并使用。在这种情况下,无需xticklabels
调整。nodes near coords
\documentclass[border=3mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.7}
\begin{document}
\begin{tikzpicture}
\begin{axis}[ybar,
bar width=1, % with compat=1.7 or higher, a unitless number means axis units are used
ymin=0,
xtick=data,
xtick pos=left,
nodes near coords,
xticklabels={A,B,C,D,E,F,G,H},
%% if the ticks has to be between columns, the following four lines can be uncommented
%tickwidth=0,
%extra x ticks={-0.5,0.5,...,8.5},
%extra x tick labels={},
%extra x tick style={tickwidth=0.15cm}
]
% you can use "coordinates {(1,5)(2,7) ...}" instead of "table[.." if you prefer that
\addplot table[x expr=\coordindex, y index=0,row sep=\\] {5\\7\\9\\15\\8\\20\\16\\13\\};
\end{axis}
\end{tikzpicture}
\end{document}
答案2
一个肮脏的技巧解决方案。如果axis
未使用选项,则它可以工作clip=false
:
\documentclass[border=3mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}
\begin{document}
\begin{tikzpicture}
\begin{axis}[%
ybar,
ymin=0, ymax=25,
xtick=data,
xticklabel interval boundaries,
enlarge x limits=.05,
symbolic x coords = {A,B,C,D,E,F,G,H,I},
nodes near coords,
nodes near coords style={%
xshift=1.25*\pgfkeysvalueof{/pgf/bar width},
anchor=south, align=center},
]
\addplot[ybar interval,
draw=black, fill=gray!10]
coordinates{ (A, 5) (B, 7) (C, 9) (D,15)
(E, 8) (F,20) (G,16) (H,13)
(I,-1) % dummy data, clip=false is prohibited
};
\end{axis}
\end{tikzpicture}
\end{document}