TransWikia.com

How to draw curve of $f(x)=dfrac{2x^2-4x+5}{x^2+1}$ in domain $-8:9$ with tikz?

TeX - LaTeX Asked by Houcine on May 13, 2021

begin{tikzpicture}
    draw[step=2cm,gray,very thin] (-8,-1) grid (9,9);
    draw[thick,->] (-8,0) -- (9,0);
    draw[thick,->] (0,-1) -- (0,9);
    foreach x in {-6,-4,-2,0,2,4,6,8}
    draw (x cm,1pt) -- (x cm,-1pt) node[anchor=north] {$x$};
    foreach y in {2,4,6,8}
    draw (1pt, y cm) -- (-1pt, y cm) node[anchor=east]{$y$};
    draw[black, thick] (-2,-1) -- (1,2);
    draw[black, thick] (1,2) -- (7,-1);
    filldraw[black] (0,0) node[anchor=north east] {0};
    draw[black,thick,domain=-8:9] plot (x,{dfrac{2x^2-4x+5}{x^2+1})}) node[right,black]{$C_f$};
    end{tikzpicture}

One Answer

dfrac typesets a fraction. To plot it, you need to use a function that pgf understand. With a little trick you can avoid having to convert x to x, but you have to input the multiplication signs.

documentclass[tikz,border=3mm]{standalone}
begin{document}
begin{tikzpicture}
draw[step=2cm,gray,very thin] (-8,-1) grid (9,9); 
draw[thick,->] (-8,0) -- (9,0); 
draw[thick,->] (0,-1) -- (0,9); 
foreach x in {-6,-4,-2,0,2,4,6,8} 
{unlessifnumx=0
draw (x cm,1pt) -- (x cm,-1pt) node[anchor=north] {$x$};
fi} 
foreach y in {2,4,6,8} 
{draw (1pt, y cm) -- (-1pt, y cm) node[anchor=east]{$y$};} 
draw[black,thick] (-2,-1) -- (1,2); 
draw[black, thick] (1,2) -- (7,-1); 
filldraw[black] (0,0) node[anchor=north east] {0}; 
draw [black,thick,declare function={x=x;}] plot[smooth,domain=-8:9] 
(x,{(2*x^2-4*x+5)/(x^2+1))}) node[right,black]{$C_f$};
end{tikzpicture}
end{document}

Needless to say that pgfplots makes this more convenient.

documentclass[tikz,border=3mm]{standalone}
usepackage{pgfplots}  
pgfplotsset{compat=1.17}
begin{document}
begin{tikzpicture}
begin{axis}[axis lines=middle,axis equal,
 xmin=-8,xmax=9,ymin=-1,ymax=9,
 xtick={-6,-4,-2,0,2,4,6,8},
 ytick={2,4,6,8},
 grid=major]
addplot[no marks,thick] coordinates {(-2,-1) (1,2) (7,-1)}; 
addplot[no marks,smooth,thick] {(2*x^2-4*x+5)/(x^2+1))} node[pos=1,right] {$C_f$};
end{axis}
end{tikzpicture}
end{document}

enter image description here

Correct answer by user229669 on May 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP