Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I'm using TikZ to plotting some functions for a document. For example, I want to plot 1/(x+1). So I did something like this:

\begin{tikzpicture}[>=stealth,x=3mm,y=3mm]
\draw (0,5) node[above]{\fimg $y=f(x+1)=\dfrac{1}{x+1}$};
\clip (-5,-5) rectangle (5,5);
\ejes[1]{-4}{4}{-4}{4}
\draw[samples=100] plot(\x,{1/(\x+1)});
\end{tikzpicture}

where \ejes[style]{xmin}{xmax}{ymin}{ymax} is command, that I have defined before to draw the axes (join with \fimg). My expected output for the code below was just the function, but I get this:

enter image description here

So, TikZ automagically put the vertical asymptote at x=-1. That isn't a bad thing, but now I want to have some control over it. For example I want dotted lines for vertical asymptotes. How can I do that?

share|improve this question
2  
Please only one question per question post. –  Martin Scharrer Nov 9 '11 at 7:53
    
Got it @MartinScharrer. –  leo Nov 9 '11 at 8:14
    
that is the wrong graphic if you say f(x+1). It is the output of f(x) –  Herbert Apr 18 '13 at 11:39

5 Answers 5

up vote 11 down vote accepted

TikZ doesn't actually draw the asymptotes: it simply connects the two points immediately before and after the jump. Because you use so many samples, you don't see that the line is actually slightly slanted.

Two suggestions: For drawing the plots, I would use the PGFplots package, which extends the plotting capabilities of TikZ/PGF substantially. It allows you to filter out coordinates above or below a certain threshold, and interrupt the plot line at that point. For drawing the asymptotes, I would use a normal \draw command. If you use PGFplots, you can specify the line in terms of the "data coordinate system" and in terms of the "axis coordinate system", so you can draw a vertical line that runs from the bottom of the plot at a specified horizontal coordinate to the top of the plot.

I've defined a new style ejes=<xmin>:<xmax> <ymin>:<ymax> which sets all the required parameters and draws the axes, and a new command \vasymptote{<xpos>} which draws a vertical dashed line at the desired position. It takes an optional argument which will be passed to the line, so you can change the color or thickness or dash pattern as you please.

With the style and the command, you could recreate your first image using

\tikz{\begin{axis}[ejes=-4:4 -4:4, title={$y=f(x+1)=\dfrac{1}{x+1}$}]
    \addplot {1/(x+1)};
    \vasymptote {-1}
\end{axis}}

which will yield

Here's the complete code:

\documentclass{standalone}
\usepackage{pgfplots}
\usepackage{amsmath}
\begin{document}

\newcommand{\vasymptote}[2][]{
    \draw [densely dashed,#1] ({rel axis cs:0,0} -| {axis cs:#2,0}) -- ({rel axis cs:0,1} -| {axis cs:#2,0});
}

\pgfplotsset{
    double y domain/.code 2 args={
        \pgfmathsetmacro\doubleymin{#1*2}
        \pgfmathsetmacro\doubleymax{#2*2}
    },
    ejes/.style args={#1:#2 #3:#4}{
        double y domain={#3}{#4},
        domain=#1:#2,
        ymin=#3,ymax=#4, restrict y to domain=\doubleymin:\doubleymax,
        samples=100,
        enlargelimits=false,
        axis lines=middle,
        xtick={#1,...,#2}, ytick={#3,...,#4},
        xticklabels=\empty, yticklabels=\empty,
        every axis plot post/.style={
            black,
            mark=none,
            smooth
        },
        scale only axis,
        width=4cm,
        height=4cm
    }
}


\tikz{\begin{axis}[ejes=-4:4 -4:4,title={$y=f(x+1)=\dfrac{1}{x+1}$}]
    \addplot {1/(x+1)};
    \vasymptote {-1}
\end{axis}}

\end{document}
share|improve this answer
1  
You could also implement this as a key to axis by \pgfplotsset{vasymptote/.style={before end axis/.append code={\draw[densely dashed] ({rel axis cs:0,0} -| {axis cs:#1,0}) -- ({rel axis cs:0,1} -| {axis cs:#1,0});}}. Maybe could even get the optional argument the style declaration. –  Matthew Leingang Nov 30 '12 at 3:33
    
How would you create a similar \hasymptote command? –  Xenon Mar 24 '13 at 3:23
    
@Jake If I pass color=red for the first parameter of \vasymptote I get 'Package PGF Math Error: Unknown function 'color' (in 'color=red').' –  Geoff Pointer Mar 22 at 1:09

With PSTricks.

enter image description here

\documentclass[pstricks,border=12pt]{standalone}
\usepackage{pst-plot}
\def\f(#1){1/(#1)}

\begin{document}
\begin{pspicture}(-4,-4)(2,4)   
    \psline[linecolor=gray,linestyle=dashed](-1,-4)(-1,3.5)
    \psaxes{->}(0,0)(-4,-4)(1.5,3.5)[$x$,0][$y$,90]
    \psset{algebraic,linecolor=blue}
    \psplot{-3.5}{-1.3}{\f(x+1)}
    \psplot{-0.7}{1}{\f(x+1)}
\end{pspicture}
\end{document}

EDIT:

Based on the comment given by texenthusiast below,

I upvoted thinking your answer is different from Herbert's as i have no idea. It would be better to mention it what's the difference.

here are the differences:

  • I used the default plotpoints=50. It should be enough. Increasing this value makes the resulting PDF bigger in file size.
  • I split the graph into 2 parts with the asymptotic line as the separator. I chose an offset of 0.3 (by inspection) to shift the domain a bit to avoid too large y values. For the current PSTricks implementation, the end points of the asymptotic graph near its asymptotic line oscillate. Fluctuation can be controlled by plotpoints key. Splitting it into 2 parts and offsetting the domain freeing me from increasing plotpoints from its default. Herbert used a single \psplot but with plotpoints=1000 to minimize the fluctuation. Thus the differences are pessimistic and optimistic approaches.
share|improve this answer
    
I upvoted thinking your answer is different from Herbert's as i have no idea. It would be better to mention it what's the difference.. –  texenthusiast Apr 17 '13 at 16:33

Alternative approach to plot asymptote using gnuplottex package with automatic underhood gnuplot computation.

Works with: -shell-escape enabled and gnuplot 4.4,

code compiled with: pdflatex,frozen texlive distro 2012 on Linux

self descriptive gnuplot code:

\documentclass[preview=true,12pt]{standalone}
\usepackage[T1]{fontenc}
\usepackage{lmodern} 
% http://www.ctan.org/pkg/gnuplottex
% amsmath for math labels
% code compiled with pdflatex engine via frozen texlive 2012 on Linux  
\usepackage{gnuplottex,amsmath} % need shell-escape enabled and gnuplot 4.4
\begin{document} 
\begin{gnuplot}[terminal=epslatex,terminaloptions=color]
                                        # means comments in gnuplot syntax
  unset border                          # border off
  unset grid                            # grid off
  unset key                             # dataset legends off
  set format x ''                       # xtics without labels
  set format y ''                       # ytics without labels
  set size square                       # figure into square size
  # xy co-ordinates range
  xmin=-3;xmax=3;ymin=-15;ymax=15;
  set samples 100                       # no of divisions xaxis xmin to  xmax
  set zeroaxis                          # x axis and y-axis aligned to origin
  set xrange [xmin:xmax]                # plot range x and y
  set yrange [ymin:ymax]
  set arrow from xmin,0 to xmax,0  filled   # xaxis starting (x,y) to ending
  set arrow from 0,ymin to 0,ymax  filled   # yaxis starting to ending
  # dotted line at discontinuity
  set arrow from -1,ymin to -1,ymax  nohead linestyle 2 linewidth 3 linecolor rgb 'black' 
  set xtics axis                        # x major ticks 
  set ytics axis                        # y major ticks 
  set title 'Asymptote $y=f(x+1)=\dfrac{1}{x+1}$ function in gnuplot'
  #set xlabel "$x$"
  #set ylabel "$f(x+1)$" rotate by 0 offset 20 
                                         # Piecewise func with ternary operator
  a(x) = x<-1  ? 1.0/(x+1) : 1/0         #  continous in x < -1
  #b(x) = x=-1  ?      inf    : 1/0      #  will not plot at discontinous x= -1
  c(x) = x>-1  ? 1.0/(x+1) : 1/0         #  continous in x > -1
  plot a(x) linetype 1 linewidth 3 linecolor rgb 'gray',c(x) linetype 1 linewidth 3 linecolor rgb 'gray'
\end{gnuplot}
\end{document}

output:

enter image description here

share|improve this answer
    
\frac{1}{x+1} without () should be enough. –  Please don't touch Apr 17 '13 at 15:21
    
@Bugbusters Thanks,\dfrac{}{} seems to be better, –  texenthusiast Apr 17 '13 at 15:25
    
Didn't know about gnuplottex. Thanks! –  Matthew Leingang Apr 17 '13 at 15:29
    
@MatthewLeingang hope you had chance to see erf function in pgfplots gnuplot matlab i am trying out options. –  texenthusiast Apr 17 '13 at 15:39
    
@texenthusiast very nice. –  Matthew Leingang Apr 17 '13 at 16:07

enter image description here

Why not to plot a vertical asymptote with the Asymptote? A slight modification of the Asymptote example 1overx.asy, 1overxplus1.asy:

import graph;
import math; // needed for drawline()
size(250,IgnoreAspect);

texpreamble("\usepackage{lmodern}"  // for the text font
+"\usepackage{amsmath}");           // for the \dfrac

real f(real x) {return 1/(x+1);};

real xmin=-4.8;
real xmax=3.8;

real epsi=1e-2;

bool3 branch(real x)  // an extended boolean type that can take on the values true, default, or false.
                      //A bool3 type can be cast to or from a bool. 
{
  static int lastsign=0;
  if(abs(x+1)<epsi) return false;
  int sign=sgn(x+1);
  bool b=lastsign == 0 || sign == lastsign; 
  lastsign=sign;
  if(b){
    return true;
  }else{
    return default;
  }
}

pen lowBranchPen=blue+1.2pt;
pen highBranchPen=red+1.2pt;
pen dashed=linetype(new real[] {4,3}); // set up dashed pattern
pen asyPen=olive+dashed+1pt;

guide[] g=graph(f,-4.8,2.8,branch);  // returns an array of curve branches according to branch function
draw(g[0],lowBranchPen);
draw(g[1],highBranchPen);
drawline((-1,-1),(-1,1),asyPen);    // draws a visible portion of the (infinite) line 
                                    // going through two points 

xaxis("$x$",LeftTicks(Label(LeftSide),NoZero));
yaxis("$y$",RightTicks(Label(RightSide),NoZero,Step=3,step=1.5));

label("$f(x)=\dfrac1{x+1}$",(-3,9));

Run asy -f pdf 1overxplus1.asy to get a standalone 1overxplus1.pdf.

share|improve this answer

with PSTricks (run with xelatex)

\documentclass[pstricks]{standalone}
\usepackage{pst-plot}
\begin{document}
\begin{pspicture}(-4.25,-4.25)(4.25,4.25)
\psaxes[labels=none,ticksize=0 4pt]{->}(0,0)(-4,-4)(4,4)[$x$,-90][$y$,0]
\psplot[algebraic,linewidth=1.5pt,linecolor=blue,yMaxValue=4,plotpoints=1000]{-4}{4}{1/(x+1)}
\psline[linestyle=dashed](-1,-4)(-1,4)
\rput(2,3){$\displaystyle f(x)=\frac1{x+1}$}
\end{pspicture}
\end{document} 

enter image description here

And if one wants exactly min/max values for the function then it can be clipped:

\documentclass[pstricks]{standalone}
\usepackage{pst-plot}
\begin{document}
\begin{pspicture}(-4.25,-4.25)(4.25,4.25)
\psaxes[labels=none,ticksize=0 4pt]{->}(0,0)(-4,-4)(4,4)[$x$,-90][$y$,0]
\psclip{\psframe[linestyle=none](-4,-4)(4,4)}
\psplot[algebraic,linewidth=1.5pt,linecolor=blue,yMaxValue=4.5,plotpoints=1000]{-4}{4}{1/(x+1)}
\endpsclip
\psline[linestyle=dashed](-1,-4)(-1,4)
\rput(2,3){$\displaystyle f(x)=\frac1{x+1}$}
\end{pspicture}
\end{document} 

However, it's often not needed!

share|improve this answer
    
is it possible to remove labels on axis as OP had in Q ? –  texenthusiast Apr 17 '13 at 15:35
    
sure, \psaxes[labels=none]{->}... –  Herbert Apr 17 '13 at 15:38
    
there is only one demo of using gnuplot with pstricks, do you have any of them hosted anywhere ? because some of features of gnuplot are good enough to show some demo. Also there is not much mentioned in pstricks manual except ref 24. I will have a look at pst-plot as well. –  texenthusiast Apr 17 '13 at 15:48
    
@texenthusiast: no, there are no more examples and yes, gnuplot is really powerful but has a lousy output –  Herbert Apr 17 '13 at 15:49
    
@Herbert in what way lousy means, legends, fonts,labels etc but with the terminal advancements (latex,pstricks pdf epslatex tikz etc), it looks better. see my answer for this Q. In pstricks documentation do you have something written about calling gnuplot from pst-plot like \addplot gnuplot{} handle to help newbies understand. –  texenthusiast Apr 17 '13 at 15:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.