我正在绘制一个带有垂直条(ybar)的图表,其中每个条代表的不是数字(1)而是类([-0.5,0.5])。
我希望 x 轴上的刻度标签出现在刻度标记附近,这样可以标记每个间隔/类别的界限,而不是它们在条形图中心的实际显示方式。我该怎么做?
我的代码:
\documentclass{article}
% ---------------------------------- tikz
\usepackage{pgfplots} % to print charts
\pgfplotsset{compat=1.8}
%
\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}
\begin{axis} [
% general
ybar interval,
scale only axis,
height=0.5\textwidth,
width=\textwidth,
ylabel={Dots numbers},
xlabel={Variation},
xticklabel style={
rotate=90,
anchor=east,
},
minor xtick={-6,...,6},
enlargelimits=false,
]
\addplot table [
x=grade,
y=value,
] {
grade value
-7 0
-6 0
-5 3
-4 1
-3 2
-2 15
-1 11
0 179
1 8
2 1
3 0
4 1
5 2
6 0
7 0
};
\end{axis}
\end{tikzpicture}
\end{figure}
\end{document}
图表如下:
答案1
您可以对标签应用移位。不过,我想向您推荐另一种方法,即将标签显示为间隔。下面我展示了两种替代方案:
\documentclass{article}
% ---------------------------------- tikz
\usepackage{pgfplots} % to print charts
\usepackage{etoolbox}
\pgfplotsset{compat=1.11}
%
\begin{document}
\begin{tikzpicture}
\begin{axis} [
% general
ybar interval,
scale only axis,
height=0.5\textwidth,
width=\textwidth,
ylabel={Dots numbers},
xlabel={Variation},
x tick label as interval=true,
xticklabel={
$[\pgfmathprintnumber{\tick},\pgfmathprintnumber{\nexttick}\pgfmathparse{int(\tick)}\ifnum\pgfmathresult=6\relax]\else)\fi$
},
xtick=data,
xticklabel style={
rotate=90,
anchor=east,
},
minor xtick={-6,...,6},
enlargelimits=false,
]
\addplot table [
x=grade,
y=value,
] {
grade value
-7 0
-6 0
-5 3
-4 1
-3 2
-2 15
-1 11
0 179
1 8
2 1
3 0
4 1
5 2
6 0
7 0
};
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis} [
% general
ybar interval,
scale only axis,
height=0.5\textwidth,
width=\textwidth,
ylabel={Dots numbers},
xlabel={Variation},
xticklabel style={
rotate=90,
anchor=south east,
yshift=0.5*\pgfplotbarwidth
},
minor xtick={-6,...,6},
enlargelimits=false,
]
\addplot table [
x=grade,
y=value,
] {
grade value
-7 0
-6 0
-5 3
-4 1
-3 2
-2 15
-1 11
0 179
1 8
2 1
3 0
4 1
5 2
6 0
7 0
};
\end{axis}
\end{tikzpicture}
\end{document}