图表不在网格内

图表不在网格内

我使用 tikz 在 Latex 中绘制了两个简单函数。它看起来像这样:
在此处输入图片描述



如您所见,曲线没有停留在网格内。我该如何修复这个问题?

这是我的代码。我使用 documentclass 'article':

\begin{tikzpicture}
  \draw[step=1cm,color=gray!20] (-5,-5) grid (5,5);
  \draw[-] (-5,0) -- (5,0) node[right] {$x$};
  \draw (0,0) node[below left] {$O$};
  \draw[-] (0,-5) -- (0,5) node[above] {$y$};
  \foreach \x in {-5, -4, -3, -2, -1, 1, 2, 3, 4, 5}
    \draw (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north] {$\x$};
  \foreach \y in {-5, -4, -3, -2, -1, 1, 2, 3, 4, 5}
    \draw (1pt,\y cm) -- (-1pt,\y cm) node[anchor=east] {$\y$};  
  \draw[scale=0.5,domain=-3:3,smooth,variable=\x,blue] plot ({\x},{\x^3});
  \draw[blue] (1,5) node[below right] {$y=x^3$};
  \draw[scale=0.5,domain=-3:3,smooth,variable=\y,red]  plot ({\y*\y},{\y});
\end{tikzpicture}

答案1

您可以使用适当的矩形剪辑:

\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
  \draw[step=1cm,color=gray!20] (-5,-5) grid (5,5);
  \draw[-] (-5,0) -- (5,0) node[right] {$x$};
  \draw (0,0) node[below left] {$O$};
  \draw[-] (0,-5) -- (0,5) node[above] {$y$};
  \foreach \x in {-5, -4, -3, -2, -1, 1, 2, 3, 4, 5}
    \draw (\x cm,1pt) -- (\x cm,-1pt) node[anchor=north] {$\x$};
  \foreach \y in {-5, -4, -3, -2, -1, 1, 2, 3, 4, 5}
    \draw (1pt,\y cm) -- (-1pt,\y cm) node[anchor=east] {$\y$};  
  \clip (-5,-5) rectangle (5,5);
  \draw[scale=0.5,domain=-3:3,smooth,variable=\x,blue] plot ({\x},{\x^3});
  \draw[blue] (1,5) node[below right] {$y=x^3$};
  \draw[scale=0.5,domain=-3:3,smooth,variable=\y,red]  plot ({\y*\y},{\y});
\end{tikzpicture}

\end{document}

结果:

在此处输入图片描述

不过,在这种情况下,我建议你改用pgfplots而是使用其内置功能来绘制图形;一个简单的例子:

\documentclass{article}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
  axis lines=middle,
  domain=-5:5,
  xtick={-5,-4,...,5},
  ytick={-5,-4,...,5},
  xmin=-5,
  xmax=5,
  ymin=-5,
  ymax=5,
  grid
  ]
  \addplot[blue,samples=100] {x^3};
  \addplot[red,domain=0:5,samples=100] {sqrt(x)};
  \addplot[red,domain=0:5,samples=100] {-sqrt(x)};
  \node[anchor=north west,blue] at (axis cs:2,5) {$y=x^{3}$};
\end{axis}
\end{tikzpicture}

\end{document}

结果:

在此处输入图片描述

相关内容