我正在做一个学校项目,我需要创建一个像这样的图表。我创建了图表,但不知道如何添加垂直虚线红线...
\begin{tikzpicture}[>=latex]
\begin{axis}[
axis lines = middle,
xlabel = $t$,
ylabel = {$x(t)$},
xtick={-50,-40,...,50},
ytick={-2,-1,...,2},
xmin=-50.5,
xmax=50.5,
ymin=-2.5,
ymax=2.5,
width=155mm,
height=70mm,
]
\addplot[
scatter,
domain=-50:50,
samples=120,
color=blue,
]
{sin(180*x/12)+cos(180*x/8)};
\addplot[
only marks,
domain=-50:50,
samples=120,
color=red
]
{sin(180*x/12)+cos(180*x/8)};
\end{axis}
\end{tikzpicture}
这是我创建的代码和图表。
答案1
ycomb
我使用选项中的虚线解决了这个问题
\documentclass[margin=3mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}
\begin{document}
\begin{tikzpicture}[>=latex]
\begin{axis}[
axis lines = middle,
xlabel = $t$,
ylabel = {$x(t)$},
xtick={-50,-40,...,50},
ytick={-2,-1,...,2},
xmin=-50.5,
xmax=50.5,
ymin=-2.5,
ymax=2.5,
width=155mm,
height=70mm,
]
\addplot[
scatter,
domain=-50:50,
samples=120,
color=blue,
]
{sin(180*x/12)+cos(180*x/8)};
\addplot[
only marks,
domain=-50:50,
samples=120,
color=red
]{sin(180*x/12)+cos(180*x/8)};
\addplot[
ycomb,
dashed,
domain=-50:50,
samples=120,
color=red
]
{sin(180*x/12)+cos(180*x/8)};
\end{axis}
\end{tikzpicture}
\end{document}
答案2
上述内容的优化版本:
- 您可以通过将它们添加到环境选项中来
domain=-50:50,samples=120,
避免重复;\addplot
axis
- 绘图
scatter
完全不需要:它会生成另一种类型的绘图,根据给定变量的值对标记进行着色。因此,您只需要两个\addplot
命令(一个用于蓝线,另一个用于梳状图); - 你可以用情节来绘制标记
ycomb
; - 最后,您可以使用该选项仅编写一次函数表达式
declare function
。
这导致以下 MWE:
\documentclass[margin=3mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\begin{document}
\begin{tikzpicture}[>=latex]
\begin{axis}[
axis lines = middle,
xlabel = $t$,
ylabel = {$x(t)$},
xtick = {-50,-40,...,50},
ytick = {-2,-1,...,2},
xmin = -50.5,
xmax = 50.5,
ymin = -2.5,
ymax = 2.5,
width = 155mm,
height = 70mm,
domain = -50:50,
samples = 120,
declare function = {%
F1 = 1/12;
F2 = 1/8;
lincomb(\t) = sin(180*F1*\t)+cos(180*F2*\t);
},
]
\addplot [color=blue] {lincomb(x)};
\addplot[
ycomb,
mark = *,
mark options = {scale = 0.75,fill = red},
color = red,
dashed,
] {lincomb(x)};
\end{axis}
\end{tikzpicture}
\end{document}