我正在使用 pgfplot 绘制正弦函数,并希望使用 pi 的倍数(pi/4、pi/2、2*pi……)标记 x 轴的刻度,因为它们是研究正弦函数时要可视化的“重要”x 值。
\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}
\begin{document}
\begin{tikzpicture}
\begin{axis}[domain=0:2*pi, ymax=1.2, samples=100, grid=major,
xlabel=$\alpha$, ylabel=$sin(\alpha)$,
xtick = {0,1,...,6}, ytick = {-1,-0.5,...,1}] %I assume this the part that I need to change?
\addplot [blue](\x, {sin(\x r)});
\end{axis}
\end{tikzpicture}
\end{document}
我尝试在上面代码中 % 附近的括号中给出 pi 的常规值,但使用“pi”或“\pi”都没有用。我是不是漏掉了什么?使用上面的代码绘制的图如下所示:
答案1
一个(简单的)替代方案:
- 绘图
sin(x)
(以度为单位) 标签勾选
0
,,\frac{\pi}{4}
....\documentclass[margin=3mm]{standalone} \usepackage{pgfplots} \pgfplotsset{compat=1.14} \begin{document} \begin{tikzpicture} \begin{axis}[ grid, ymax = 1.2, xlabel = $\alpha$, ylabel=$\sin(\alpha)$, xtick = {0,45,...,360}, xticklabels = {\mathstrut 0, $\frac{ \pi}{4}$,$\frac{ \pi}{2}$,$\frac{3\pi}{4}$,$\mathstrut \pi$, $\frac{5\pi}{4}$,$\frac{3\pi}{2}$,$\frac{7\pi}{4}$,$\mathstrut2\pi$}, domain = 0:360, samples = 73, no marks ] \addplot +[very thick] {sin(x)}; \end{axis} \end{tikzpicture} \end{document}
答案2
欢迎来到 TeX.SE!这里有一个可能性。请注意,存在数字格式frac
,但在这种情况下我无法使其工作。
\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}
% based on https://tex.stackexchange.com/a/34958/121799
\foreach \X [count=\Y] in {0,...,8}
{\pgfmathsetmacro{\myx}{\X*pi/4}
\ifnum\Y=1
\xdef\LstX{\myx}
\else
\xdef\LstX{\LstX,\myx}
\fi
}
\begin{tikzpicture}
\begin{axis}[domain=0:2*pi, ymax=1.2, samples=100, grid=major,
xlabel=$\alpha$, ylabel=$\sin(\alpha)$,
xtick=\LstX,
xticklabel={\pgfmathtruncatemacro{\tmp}{round(4*\tick/pi)}
\pgfmathsetmacro{\mygcd}{gcd(\tmp,4)}%
\pgfmathtruncatemacro{\mynumerator}{\tmp/\mygcd}%
\pgfmathtruncatemacro{\mydenominator}{4/\mygcd}%
\ifnum\mynumerator=0
$\mathstrut\pgfmathprintnumber{0}$
\else
\ifnum\mynumerator=1
\ifnum\mydenominator=1
$\mathstrut\pi$
\else
$\frac{\pi}{\pgfmathprintnumber{\mydenominator}}$
\fi
\else
\ifnum\mydenominator=1
$\mathstrut\mynumerator\pi$
\else
$\frac{\mynumerator\pi}{\pgfmathprintnumber{\mydenominator}}$
\fi
\fi
\fi}, % https://tex.stackexchange.com/a/304032/121799
ytick = {-1,-0.5,...,1}] %I assume this the part that I need to change?
\addplot [blue](\x, {sin(deg(\x))});
\end{axis}
\end{tikzpicture}
\end{document}