我正在用 绘制条形图pgfplots
。我需要将每列的值放在列本身上方,如下所示:
图1
但 LaTeX 将其置于左侧上方的中心:
图 2
我尝试使用nodes near coords align={vertical}
和nodes near coords align={horizontal}
作为axis
环境的选项,但第一个没有任何作用,而第二个使情况变得更糟:
图 3
我怎样才能将标签放在我想要的位置,而不会相互重叠,也不会与附近的列重叠(参见图 2 中列4000
中的值90
)?我还想隐藏“隐藏”列的标签100
(在图 2 和图 3 中可见)。
这是源代码的简化版本(可能缩进过多,但我觉得更清晰):
\documentclass[twocolumn]{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[xtick=data,
xtick pos=left,
xticklabel interval boundaries,
ybar,
ymin=0,
scaled y ticks=false,
nodes near coords,
symbolic x coords={$0$,$10$,$20$,$30$,$40$,$50$,$60$,$70$,$80$,$90$,$100$}]
\addplot [ybar interval,fill=lightgray]
coordinates {($0$, 5) ($10$, 0) ($20$, 15)
($30$, 75) ($40$, 250) ($50$, 1000)
($60$, 3000) ($70$, 7000) ($80$, 11000)
($90$, 4000) ($100$, 0)};
\end{axis}
\end{tikzpicture}
\end{document}
注意:类选项twocolumn
似乎与标签对齐相关。
答案1
请尝试以下操作:
\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}
\begin{document}
\begin{center}
\begin{tikzpicture}
\begin{axis}[
width=\linewidth,
xtick=data,
xticklabel interval boundaries,
ybar,
%bar width=9mm,
ymin=0,
scaled y ticks=false,
nodes near coords,
nodes near coords style = {font=\footnotesize, anchor=south west,
text width=8mm, inner xsep=0pt, align=center},
symbolic x coords={$0$,$10$,$20$,$30$,$40$,$50$,$60$,$70$,$80$,$90$,$100$}
]
\addplot [ybar interval,fill=lightgray]
coordinates {($0$, 5) ($10$, 0) ($20$, 15)
($30$, 75) ($40$, 250) ($50$, 1000)
($60$, 3000) ($70$, 7000) ($80$, 11000)
($90$, 4000) ($100$, 0)};
\end{axis}
\end{tikzpicture}
\end{center}
\end{document}
附录:
根据您的评论,图表的宽度等于columnwidth
并且条形的标签可以旋转:
\documentclass[twocolumn]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}
\usepackage{lipsum}
\begin{document}
\lipsum[11]
\begin{figure}[ht]
\begin{tikzpicture}
\begin{axis}[
width=\linewidth,
ybar,
xtick=data,
xticklabel interval boundaries,
ytick distance=2000,
xticklabel style= {font=\footnotesize},
xmax=110, ymin = 0, % had to be smaller than y coordinate
% of dummy data y coordinate
enlarge x limits=0.05,
enlarge y limits={value=.3,upper},
scaled y ticks=false,
nodes near coords,
nodes near coords style = {font=\small,
xshift=0.75*\pgfkeysvalueof{/pgf/bar width},
rotate=90, anchor=west},
symbolic x coords={0,10,20,30,40,50,60,70,80,90,100,110}
]
\addplot [ybar interval,fill=lightgray]
coordinates {(0, 5) (10, 0) (20, 15) (30, 75)
(40, 250) (50,1000) (60,3000) (70,7000)
(80,11000) (90,4000) (100, 0) (100, 0)
(110,-100) % dummy coordinate,
}; % option clip=false is prohibited
\end{axis}
\end{tikzpicture}
\caption{Diagram}
\label{fig:diagram}
\end{figure}
See diagram on figure {fig:diagram}
\lipsum[1-4]
\end{document}