我有以下 MWE
\documentclass[tikz,border=2mm]{standalone}
\begin{document}
\begin{tikzpicture}[domain=-1:6]
\draw[very thin, color=green, step=0.2cm](-2,-3) grid (7,11);
\draw[color=cyan](-2,-3) grid (7,11);
\draw[->,ultra thick] (-2,0)--(7,0) node[below]{$x$};
\draw[->,ultra thick] (0,-3)--(0,11) node[left]{$y$};
\foreach \x in {-1,0,...,6}
\draw (\x cm, 1pt)--(\x cm,-1pt) node[anchor=north] {$\x$};
\foreach \y in {-2,-1,...,10}
\draw (1pt, \y cm)--(-1pt, \y cm) node[anchor=east] {$\y$};
\draw[color=black, thick] plot (\x,\x^2-5*\x+4) node[]{$y=x^2-5x+4$};
\end{tikzpicture}
\end{document}
问题是第一个坐标应该是 (-1,10),但我的代码绘制的是 (-1,8)。其他点似乎没问题。函数是 y=x²-5x+4
请告知,我的请求如下:
- 帮助我修正此代码,以便图形能够按应有的方式通过 (-1,10),而不是 (-1,8)
- 如果标签(y=x²-5x+4)倾斜并沿着曲线而不是悬挂在顶部,我会很高兴。
答案1
问题的根源\x^2
在于您的功能。正确答案是(\x)^2
。
尝试:
\documentclass[tikz,border=2mm]{standalone}
\usetikzlibrary{arrows.meta}
\begin{document}
\begin{tikzpicture}[
arr/.style = {very thick, draw=gray, -{Straight Barb[length=1mm]}},
domain=-1:6, samples=70
]
\draw[very thin, color=green, step=0.2cm](-2,-3) grid (7,11);
\draw[color=cyan](-2,-3) grid (7,11);
\draw[arr] (-2,0) -- (7, 0) node[below]{$x$};
\draw[arr] (0,-3) -- (0,11) node[left]{$y$};
% tick labels
\foreach \x in {-1,0,...,6}
\draw (\x, 1pt) -- ++ (0,-1pt) node[below left] {$\x$};
\foreach \y in {-2,-1,...,10}
\draw (1pt, \y) -- ++ (-1pt, 0) node[below right] {$\y$};
% function
\draw[color=black, thick] plot (\x,{(\x)^2 - 5*\x+4})
node[anchor=north east, rotate=80] {$y=x^2-5x+4$};
\end{tikzpicture}
\end{document}
答案2
这是另一种解决方案pgfplots
,我没有改变你的情节命令。
输出
代码
\documentclass[margin=10pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.17}
\begin{document}
\begin{tikzpicture}
\begin{axis}[%
domain=-1:6,
yscale=2,
axis lines=middle,
xlabel={\large $x$},
ylabel={\large $y$},
xtick={-1,...,6},
ytick={-2,...,10},
ymin=-3,
ymax=11,
xmin=-2,
xmax=7,
grid=both,
grid style={line width=.1pt, green},
major grid style={line width=.2pt,cyan},
minor tick num=4,
tick style={draw=none},
extra x ticks={-2,6,7},
extra y ticks={-3,10,11},
extra x tick labels={},
extra y tick labels={},
extra x tick style={grid=both},
extra y tick style={grid=both},
]
\addplot[thick,smooth, cyan!50!green] (\x,\x^2-5*\x+4) node[]{$y=x^2-5x+4$};
\end{axis}
\end{tikzpicture}
\end{document}