我有一个 y 轴上有间隔的 const 图。我希望 y 标签在每个条形中居中,就像这是 xbar 间隔图一样。
此外,更重要的是,我希望 y 标签间隔具有更大的灵活性和控制力。例如,我是否可以包含每个其他间隔,如 [0,.05) [.1,.15) 等,并在其间留出间隙?
最后,有没有一种简单的方法可以让最后一个间隔在两边都变成闭括号?
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
height=10cm,
const plot,
y tick label as interval=true,
ytick=,
yticklabel={$[\pgfmathprintnumber\tick, \pgfmathprintnumber\nexttick)$},
enlargelimits=false,
ymin=0,
xmin=0
]
\addplot [fill=blue,opacity=.6,draw=blue]
coordinates
{(0,0) (393,0.000) (93,0.050) (44,0.100) (49,0.150) (31,0.200) (32,0.250) (37,0.300) (52,0.350) (90,0.400) (30,0.450) (26,0.500) (11,0.550) (32,0.600) (31,0.650) (15,0.700) (33,0.750) (18,0.800) (25,0.850) (31,0.900) (162,0.950) (0,1)};
\end{axis}
\end{tikzpicture}
\end{document}
答案1
要为每个条形获取一个标签,您可以设置ytick=data
。要获取闭区间,您可以使用内联检查来查看 bin 的上限是否为 1,使用\ifdim\nexttick pt=1pt ] \else ) \fi
(\ifdim
需要它比较的值有单位,这就是我们使用的原因pt
)。为了确保所有内容都对齐,您应该使用\pgfmathprintnumber[fixed, fixed zerofill]{...}
,并使用\leavevmode\rlap{]}\hphantom{)}
(如egreg 好心地告诉我)。
如果只打印一些标签,通常可以使用ytick={0,0.1,...,1}
,但在间隔刻度的情况下,它不会按照您的要求执行操作(它会绘制0-0.1, 0.1-0.2
,而您想要0-0.05,0.1-0.15
),因此我们必须做其他事情:我们可以引入一个计数器,该计数器在每个刻度上递增,并且在每个刻度上,我们使用 检查计数器值是否可以被 2(或 3 或其他)整除\pgfmathparse
。如果是,我们打印刻度标签,如果不是,则不打印:
\documentclass{article}
\usepackage{pgfplots}
\begin{document}
\newcounter{ticknumber}
\setcounter{ticknumber}{1}
\makeatletter
\begin{tikzpicture}
\begin{axis}[
height=10cm,
const plot,
y tick label as interval=true,
ytick=data,
yticklabel={%
\pgfmathtruncatemacro\isdivisible{Mod(\theticknumber,2)==0}
\ifnum\isdivisible=1
$[\pgfmathprintnumber[fixed, fixed zerofill]\tick, \pgfmathprintnumber[fixed, fixed zerofill]\nexttick\ifdim\nexttick pt=1pt \leavevmode\rlap{]}\hphantom{)} \else ) \fi$
\fi
\stepcounter{ticknumber}
},
enlargelimits=false,
ymin=0,
xmin=0
]
\addplot [fill=blue,opacity=.6,draw=blue]
coordinates
{(0,0) (393,0.000) (93,0.050) (44,0.100) (49,0.150) (31,0.200) (32,0.250) (37,0.300) (52,0.350) (90,0.400) (30,0.450) (26,0.500) (11,0.550) (32,0.600) (31,0.650) (15,0.700) (33,0.750) (18,0.800) (25,0.850) (31,0.900) (162,0.950) (0,1)};
\end{axis}
\end{tikzpicture}
\end{document}