我想在轴标签中设置可变精度,这样标签中只有两个有效数字。例如,轴标签可能是 0.20、0.40、0.60、0.80、1.0、1.2 等。
y tick label style={/pgf/number format/.cd,
/tikz/.cd}
答案1
通常情况下,有一个fixed relative
键原则上可以满足您的要求。但不幸的是 - 正如手册中所述 - 此键会忽略该zerofill
键,因此数字后面不会有零(参见 MWE 中的 x 轴标签)。
但是我们可以用来siunitx
打印数字,这样就可以满足您的需求。只有零本身才会打印为“0”。这就是我为此添加特殊处理程序的原因。
\documentclass[border=2pt]{standalone}
\usepackage{pgfplots} % v1.14
\usepackage{siunitx} % v2.6s
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ymin=-1.2,
ymax=1.2,
ytick distance=0.2,
% -------------------------------------------------------------
% change number format of `x tick label's
x tick label style={
/pgf/number format/.cd,
% using `fixed relative' would normally work ...
fixed relative,
precision=2,
% ... but `zerofill' is ignored for the `fixed relative'
% key, so here it will not give the desired result
zerofill,
/tikz/.cd,
},
% -------------------------------------------------------------
% change `yticklabel' to fit your needs
yticklabel={
% use special handler for "0.", because this gives an undesired
% result with `\num' (see below)
% (I assume that this strange behavior is a bug)
\ifdim\tick pt=0pt
% Therefore use the "normal" tikz features to plot "0"
\pgfmathprintnumber[
fixed,
precision=2,
zerofill,
]{\tick}
\else
% and use `\num' for all other numbers
\num[
round-mode=figures,
round-precision=2,
]{\tick}
\fi
},
% -------------------------------------------------------------
]
\addplot {x};
\sisetup{
round-mode=figures,
round-precision=2,
add-decimal-zero=true, % <-- default
}
\draw (axis cs:0,0)
% without trailing decimal separator
node [above,green!80!black] {\num{0}}
% with trailing decimal separator
node [below,red!80!black] {\num{0.}} % same for `0.0'
;
\end{axis}
\end{tikzpicture}
\end{document}