Search code examples
mathgnuplotgaussiangraphing

Gaussian peaks not overlapping in Gnuplot


I’m trying to plot multiple Gaussian functions on the same graph with Gnuplot, which is quite a simple thing. The problem is that the peaks do not overlap and I get the following result that looks like they have different peaks, which they don’t. How can I fix this?

ugly thing


Solution

  • First, it helps to understand how gnuplot generates plots of functions (or really how any computer program must do it). It must convert a continuous function into some kind of discrete representation. The mathematical function to be plotted is evaluated at various points along the independent (x) axis. This creates a set of (x,y) points. A line is then drawn between these points (think "connect the dots"). As you might imagine, the number of discrete samples used affects how accurately the curve is represented, and how smooth it looks.

    The problem you have noticed is that the default sample size in gnuplot is a bit too low. The default (I believe) is 100 samples across the visible x-axis. You can adjust the number of samples (to 1000, for example) with

    set samples 1000
    

    I have made some example plots of gaussians to illustrate this point. (I made a rough estimate of your gaussian parameters.) Each plot has a different number of samples:

    100 samples (default) 20 samples (too low) 1000 samples (plenty high)

    Notice how the lines get too jagged if the sample size is too low. Even the default value of 100 is too low. Setting to 1000 makes it plenty smooth. This is probably more than it needs to be, but it works. If you're using a terminal that generates a bitmap image (e.g. PNG), then you shouldn't need more samples than you have width in pixels used for the x-axis plot area. If you're generating vector based output, then just pick something that "looks right" for whatever you are using it in.

    See the question Gnuplot x-axis resolution for more.


    By the way, the code to generate the above examples is:

    set terminal pngcairo size 640,480 enhanced
    
    # Line styles
    set style line 1 lw 2 lc rgb "blue"
    set style line 2 lw 2 lc rgb "red"
    set style line 3 lw 2 lc rgb "yellow"
    
    # Gaussian function stuff
    set yrange [0:1.1]
    set xrange [-20:20]
    gauss(x,a) = exp(-(x/a)**2)
    eqn(a) = sprintf("y = e^{-(x/%d)^2}", a)
    
    # First example (default)
    set output "example1.png"
    set title "100 samples (default)"
    plot gauss(x,8) ls 1 title eqn(8), \
         gauss(x,2) ls 2 title eqn(2), \
         gauss(x,1) ls 3 title eqn(1)
    
    # Second example (too low)
    set output "example2.png"
    set title "20 samples (too low)"
    set samples 20
    replot
    
    # Third example (plenty high)
    set output "example3.png"
    set title "1000 samples (plenty high)"
    set samples 1000
    replot