有人能解释一下为什么我的图不符合预期吗?该函数关于 y 轴对称。该图正确显示了 x 为正值的函数,但对负值则不正确。这是我的代码:
\documentclass[10pt]{article}
\usepackage{pgf,tikz}
\usetikzlibrary{arrows}
\usepackage{fouriernc}
\begin{document}
\begin{tikzpicture}[>=latex,x=1.3cm]
\fill[fill=lightgray] (0,0) -- plot[domain=0:1,samples=100] (\x,{sqrt(abs(\x))-\x^2});
\fill[fill=lightgray] plot[domain=1:2,samples=100] (\x,{sqrt(abs(\x))-\x^2}) -- (2,0);
\draw[thick,domain=-1:2.2,samples=100] plot (\x,{sqrt(abs(\x))-\x^2}) node[right] {\footnotesize $f(x)=\sqrt{|x|}-x^2$};
\foreach \x in {-1,1,2,3}
\draw[shift={(\x,0)},color=black] (0pt,2pt) -- (0pt,-2pt) node[below] {\footnotesize $\x$};
\foreach \y in {-3,-2,-1,1}
\draw[shift={(0,\y)},color=black] (2pt,0pt) -- (-2pt,0pt) node[left] {\footnotesize $\y$};
\draw[->,thick] (-2,0) -- (4,0) node[above left]{\footnotesize $x$};
\draw[->,thick] (0,-4) -- (0,2) node[below right]{\footnotesize $f(x)$};
\end{tikzpicture}
\end{document}
以下是我使用此代码得到的结果:
答案1
评论
在表达式中\x^2
需要用\x
括号括起来,不要问我为什么。
执行
\documentclass[tikz]{standalone}
\usetikzlibrary{arrows}
\begin{document}
\begin{tikzpicture}[>=latex,x=1.3cm]
\fill[fill=lightgray] (0,0) -- plot[domain=0:1,samples=100] (\x,{sqrt(abs(\x))-(\x)^2});
\fill[fill=lightgray] plot[domain=1:2,samples=100] (\x,{sqrt(abs(\x))-(\x)^2}) -- (2,0);
\draw[thick,domain=-1:2.2,samples=100] plot (\x,{sqrt(abs(\x))-(\x)^2}) node[right] {\footnotesize $f(x)=\sqrt{|x|}-x^2$};
\foreach \x in {-1,1,2,3}
\draw[shift={(\x,0)},color=black] (0pt,2pt) -- (0pt,-2pt) node[below] {\footnotesize $\x$};
\foreach \y in {-3,-2,-1,1}
\draw[shift={(0,\y)},color=black] (2pt,0pt) -- (-2pt,0pt) node[left] {\footnotesize $\y$};
\draw[->,thick] (-2,0) -- (4,0) node[above left]{\footnotesize $x$};
\draw[->,thick] (0,-4) -- (0,2) node[below right]{\footnotesize $f(x)$};
\end{tikzpicture}
\end{document}
输出
答案2
也许有一种更简单的方法来绘制你的函数,从而消除歧义\x^2
:
\documentclass{standalone}
\usepackage{pgfplots}
\usepackage{lmodern}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
axis on top=true,
xlabel={$x$},
ylabel={$f(x)$},
axis x line=middle,
axis y line=middle,
xmin=-2,
xmax=4.9,
ymax=1.4,
ymin=-4]
\addplot[fill=lightgray,domain=-1:2,samples=100] {sqrt(abs(x))-x^2} \closedcycle;
\addplot[domain=2:3,samples=10] {sqrt(abs(x))-x^2};
\node at (axis cs: 2,-2.2) [anchor=west] {$f(x)=\sqrt{\vert x\vert}-x^2$};
\end{axis}
\end{tikzpicture}
\end{document}