如果我绘制下图,我会得到 x 轴上的点 1020,而不是预期的 1024。有办法解决这个问题吗?
\documentclass[10pt]{article}
\usepackage{pgfplots}
\begin{document}
\begin{figure}[h]
\centering
\begin{tikzpicture}
\begin{axis}[
xmode=log,
xlabel=Threads per block,
ylabel=Time (s),
legend pos=north west,
xtick={data},
xticklabel={%
\pgfkeys{/pgf/fpu=true}%
\pgfmathparse{exp(\tick)}%
\pgfmathprintnumber[fixed relative, precision=3]{\pgfmathresult}%
\pgfkeys{/pgf/fpu=false}%
}
]
\addplot table {
1 8.87E+00
2 1.09E+01
4 8.79E+00
8 5.53E+00
16 4.53E+00
32 5.17E+00
64 5.10E+00
128 5.28E+00
256 1.00E+01
512 2.09E+01
1024 4.26E+01
};
\end{axis}
\end{tikzpicture}
\caption{Execution times when using one thread per row of the solution matrix's grid.} \label{fig:opr}
\end{figure}
\end{document}
答案1
改编
- 提高精度
precision=4
- 用于
round( ... )
获取整数 - 设置
width
并height
避免重叠
结果
代码
\documentclass[10pt]{article}
\usepackage{pgfplots}
\begin{document}
\begin{figure}[h]
\centering
\begin{tikzpicture}
\begin{axis}[
width=0.9\textwidth,
height=70mm,
xmode=log,
xlabel=Threads per block,
ylabel=Time (s),
legend pos=north west,
xtick={data},
xticklabel={%
\pgfkeys{/pgf/fpu=true}%
\pgfmathparse{round(exp(\tick))}%
\pgfmathprintnumber[fixed relative, precision=4]{\pgfmathresult}%
\pgfkeys{/pgf/fpu=false}%
}
]
\addplot table {
1 8.87E+00
2 1.09E+01
4 8.79E+00
8 5.53E+00
16 4.53E+00
32 5.17E+00
64 5.10E+00
128 5.28E+00
256 1.00E+01
512 2.09E+01
1024 4.26E+01
};
\end{axis}
\end{tikzpicture}
\caption{Execution times when using one thread per row of the solution matrix's grid.} \label{fig:opr}
\end{figure}
\end{document}
以 2^x 为刻度的变体
结果
代码
替换里面的两行xticklabel={ ... }
:
\pgfmathparse{round(ln(exp(\tick))/ln(2))}%
$2^{\pgfmathprintnumber[fixed relative, precision=4]{\pgfmathresult}}$
答案2
我想,您希望得到以下结果:
与您的 MWE 相比,有以下区别:
- 刻度之间的距离增加,标签更易于读取
- 放大 x 极限
- 已定义刻度标签样式
- 使用不同的(更简单的)方法来计算 x 刻度标签
\documentclass[margin=3mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
xmode=log,
xlabel = Threads per block,
ylabel = Time (s),
% changed styles
x = 9mm,
enlarge x limits = 0.05,
ticklabel style = {font=\footnotesize,
/pgf/number format/1000 sep={}},
log basis x = 2,
xticklabel = \pgfmathparse{2^\tick}
\pgfmathprintnumber{\pgfmathresult}
]
\addplot table {
1 8.87E+00
2 1.09E+01
4 8.79E+00
8 5.53E+00
16 4.53E+00
32 5.17E+00
64 5.10E+00
128 5.28E+00
256 1.00E+01
512 2.09E+01
1024 4.26E+01
};
\end{axis}
\end{tikzpicture}
\end{document}