我正在尝试绘制一个以 2 为底的对数轴的图,除了标签是 32、64、128、256、512 和1020. 最后一个应该是1024。我认为这与有效数字有关,但我不确定如何改变它。
以下是我正在使用的代码:
\documentclass{article}
\usepackage{pgfplots}
\usepackage[active, tightpage]{preview}
\PreviewEnvironment{tikzpicture}
\begin{document}
\begin{tikzpicture}
\begin{semilogxaxis}[
every axis legend/.append style={nodes={right}},
xlabel=$n$,
log basis x=2,
ymode=log,
ylabel=Time (sec),
log ticks with fixed point,
legend style={at={(0.05,0.95)},
title={My title},
anchor=north west}]
\addplot coordinates {
(32,0.04)
(64,0.09)
(128,0.14)
(256,0.27)
(512,0.56)
(1024,1.66)
};
\addplot coordinates {
(32,0.04)
(64,0.09)
(128,0.26)
(256,0.92)
(512,5.71)
(1024,42.14)
};
\legend{With minimization,Without minimization}
\end{semilogxaxis}
\end{tikzpicture}
\end{document}
非常感谢。
答案1
这确实是一个精度问题。
两种可能的选择:
使用
xticklabel={ \pgfkeys{/pgf/fpu=true} \pgfmathparse{int(2^\tick)} \pgfmathprintnumber[fixed]{\pgfmathresult} }
这样可以得到正确的结果
2^21 = 2097152
,但之后你也会遇到精度问题-
xticklabel={\xinttheiexpr2^\tick\relax}
这相当于几百位数字。我尝试了
2^42 = 4398046511104
,效果很好。不过,有时你可能不再需要固定格式的输出。
\documentclass{article}
\usepackage{pgfplots}
\usepackage{xintexpr}
\usepackage[active, tightpage]{preview}
\PreviewEnvironment{tikzpicture}
\begin{document}
\begin{tikzpicture}
\begin{semilogxaxis}[
every axis legend/.append style={nodes={right}},
xlabel=$n$,
log basis x=2,
ymode=log,
ylabel=Time (sec),
/pgf/number format/1000 sep={\,},
xticklabel={\xinttheiexpr[0]2^\tick\relax},
legend style={at={(0.05,0.95)},
title={My title},
anchor=north west}]
\addplot coordinates {
(32,0.04)
(64,0.09)
(128,0.14)
(256,0.27)
(512,0.56)
(1024,1.66)
};
\addplot coordinates {
(32,0.04)
(64,0.09)
(128,0.26)
(256,0.92)
(512,5.71)
(1024,42.14)
};
\legend{With minimization,Without minimization}
\end{semilogxaxis}
\end{tikzpicture}
\end{document}