我正在尝试绘制下图中的函数。
我尝试编写如下代码:
\documentclass[12pt]{article}
\usepackage[paper=letterpaper,margin=2cm]{geometry}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{pgfplots}
\usepackage{newtxtext, newtxmath}
\usepackage{enumitem}
\usepackage{titling}
\usepackage{tikz}
\usepackage[colorlinks=true]{hyperref}
\setlength{\droptitle}{-6em}
% Enter the specific assignment number and topic of that assignment below, and replace "Your Name" with your actual name.
\begin{document}
Test
\begin{tikzpicture}[
declare function={
func(\x)= (\x < 0) * (0) +
and(\x >= 0, \x < 1 * (0.5) +
(\x >= 1) * (2 * \x))
;
}
]
\begin{axis}[
axis x line=middle, axis y line=middle,
ymin=-5, ymax=5, ytick={-5,...,5}, ylabel=$y$,
xmin=-5, xmax=5, xtick={-5,...,5}, xlabel=$x$,
domain=-pi:pi,samples=101, % added
]
\addplot [blue,thick] {func(x)};
\end{axis}
\end{tikzpicture}
\end{document}
这段代码并没有产生我想要的效果。我哪里做错了?
我确实查看了论坛上的其他问题,但似乎缺少一些关于正确声明函数的理解。
答案1
试试这个代码。您需要增加样本数量才能获得函数的垂直线。
\documentclass[12pt,a4paper]{article}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}% <<<<
\begin{document}
\begin{tikzpicture}[
declare function={
funcx(\x)=
(\x < 0) * (0)) +
and(\x >= 0, \x <1) * (0.5) +
and(\x >= 1, \x <= 2) * (0.5*\x) +
(\x >= 2) * (1));
}]
\begin{axis}[
axis x line=middle, axis y line=middle,
ymin=0, ymax=2, ytick={0,0.5,...,1}, ylabel=$y$,
xmin=-1, xmax=3, xtick={0,1,...,2}, xlabel=$x$,
domain=-1:3, samples=300, % added samples
]
\addplot[thick]{funcx(x)};
\end{axis}
\end{tikzpicture}
\end{document}
选择
如果您不想要垂直线,请绘制两次函数:左侧部分和右侧部分具有不同的域。
\documentclass[12pt,a4paper]{article}
\usepackage{pgfplots}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[
declare function={
funcx(\x)=
(\x < 0) * (0)) +
and(\x >= 0, \x <1) * (0.5) +
and(\x >= 1, \x <= 2) * (0.5*\x) +
(\x >= 2) * (1));
}]
\begin{axis}[
axis x line=middle, axis y line=middle,
ymin=0, ymax=2, ytick={0,0.5,...,1}, ylabel=$y$,
xmin=-1, xmax=3, xtick={0,1,...,2}, xlabel=$x$,
samples=100, %
]
\addplot[red, domain=0.01:3, thick]{funcx(x)};
\addplot[red, domain=-1:-0.01,thick]{funcx(x)};
\end{axis}
\end{tikzpicture}
\end{document}