无法使用 pgf/tikz 绘制 x^4、sqrt(x) 或 x^3 + 5x^2

无法使用 pgf/tikz 绘制 x^4、sqrt(x) 或 x^3 + 5x^2

我最近开始使用 LateX,并开始使用 pgf/tikz 来创建图表。但我遇到了上述函数的一些问题。我可以绘制函数 f(x)=x^3,但当我尝试将 5*x^2 添加到该函数时,编译时会出现错误。当我尝试绘制 x^4 和 sqrt(x) 时,也会发生同样的情况。例如:

\documentclass{article}
\usepackage{pgfplots}
\usepackage{pgf,tikz}           
\usetikzlibrary{arrows}
\usepackage{tikz}
\usepackage [hmargin=2cm,vmargin=3cm]{geometry}
\begin{document}
\definecolor{ttqqqq}{rgb}{0.2,0,0}
\definecolor{wqwqwq}{rgb}{0.38,0.38,0.38}
\begin{tikzpicture}[line cap=round,line join=round,>=triangle 45,x=1.5923130274930888cm,y=1.0cm]
\draw[->,color=black] (-2.09,0) -- (7.96,0);
\foreach \x in {-2,-1,1,2,3,4,5,6,7}
\draw[shift={(\x,0)},color=black] (0pt,2pt) -- (0pt,-2pt) node[below] {\footnotesize $\x$};
\draw[->,color=black] (0,-4.76) -- (0,9.28);
\foreach \y in {-4,-2,2,4,6,8}
\draw[shift={(0,\y)},color=black] (2pt,0pt) -- (-2pt,0pt) node[left] {\footnotesize $\y$};
\draw[color=black] (0pt,-10pt) node[right] {\footnotesize $0$};
\clip(-2.09,-4.76) rectangle (7.96,9.28);
\draw[smooth,samples=100, domain=-2:8] plot(\x,{(\x)^(3)+2*(\x)^2});
\end{tikzpicture}
\end{document}

编译时出现错误,但是当我在 if (\x)^3 前面加上减号时,函数就是 -(\x)^3+2*(\x}^2,它可以完美地绘制函数。有谁可以解释一下吗?

答案1

正如ferahfeza提到的,您可以使用axis环境来绘制函数。以下是示例:

\documentclass{article}

\usepackage{pgfplots}

\begin{document}
\begin{tikzpicture}
\begin{axis}
  \addplot {x^4};
  \addlegendentry{$x^4$};
\end{axis}
\end{tikzpicture}
\begin{tikzpicture}
\begin{axis}
  \addplot {sqrt(x)};
  \addlegendentry{$\sqrt{x}$};
\end{axis}
\end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

使用 PSTricks 的解决方案。

\documentclass[pstricks,border=12pt,12pt]{standalone}
\usepackage{pst-plot}
\psset{algebraic}
\begin{document}
\begin{pspicture}(-2,-1)(2.5,10.5)
    \psaxes{->}(0,0)(-2,-1)(2,10)[$x$,0][$y$,90]
    \psplot[linecolor=red]{-1.5}{1.5}{x^4}
    \psplot[linecolor=green]{0}{1.5}{sqrt(x)}
    \psplot[linecolor=blue]{-1.25}{1.25}{x^3+5*x^2}
\end{pspicture}
\end{document}

在此处输入图片描述

相关内容