JustToThePoint English Website Version
JustToThePoint en español
JustToThePoint in Thai

Plotting functions

A function is a relation or rule that defines a relationship between one variable (the independent variable) and another variable (the dependent variable). A function is linear if it can be expressed in the form f(x)=mx + b. Its graph is a straight line, m is the slope, and b is the value of the function where x equals zero (it is also the point where the graph crosses the y-axis).

Gnuplot is a free, command-driven, interactive plotting program. The set grid command allows grid lines to be drawn on the plot. The set xzeroaxis command draws a line at y = 0. set xrange [-5:5] and set yrange [-60:40] set the horizontal and vertical ranges that will be displayed. plot and splot are the primary commands in Gnuplot, e.g., plot sin(x)/x, splot sin(x*y/20), or plot [-5:5] x**4 -6*x**3 +5*x**2 +24*x -36, where x**4 is x4 and -6*x**3 is -6*x3.

set terminal wxt size 400,250 enhanced font 'Verdana,12' persist 
# Use _set terminal_ to tell gnuplot what kind of output to generate. The wxt terminal device generates output in a separate window. 

set border linewidth 1.5 # _set border_ controls the display of the graph borders for the plot and splot commands.

set style line 1 linecolor rgb '#0060ad' linetype 1 linewidth 2 # _set style line_ defines a set of line types and widths and point types and sizes so that you can refer to them later by an index instead of repeating all the information at each invocation. 

set style line 2 linecolor rgb '#dddd1f' linetype 1 linewidth 2
set xzeroaxis linetype 3 linewidth 2.5 # It draws the x axis.
set xlabel 'x' # Set the label for the x-axis
set ylabel 'y' # Set the label for the y-axis
set key top left # The set key enables a key (or legend) describing plots on a plot. 
f(x)=3*x+5 # We define two linear functions
g(x)=4*x

plot f(x) title '3*x+5' with lines linestyle 1, \ # We plot f(x) using linestyle 1
     g(x) title '4*x' with lines linestyle 2 # and g(x) using linestyle 2

Gnuplot can be run interactively ([email protected]:~$ gnuplot. The environment opens in the console and you can add your commands after gnuplot>. For instance, type load ‘myPlot.gnu’) or from script files (ascii files that have commands written out just as you would enter them interactively): gnuplot myPlot.gnu. Plotting functions

Plotting functions

These are concurrent lines (they intersect each other exactly at one point) and the point of concurrence is (5, 20) (3*x +5 = 4*x; -x=-5; x = 5).

  1. We use a x-vector to store the x-values: x=-10:0.1:10; (start -10:step 0.1:end 10, it defines a sequence from start to end by adding increments of step).
  2. Define our two functions: y = x.*2; z=x.*2 + 10; We use element by element operations (x.*2, x.*2 + 10) on the x-vector to store the functions values in y-vector and z-vector. 3. Finally, we use the command plot(x, y) to plot x*2 or plot(x, y, x, z) to plot both functions. Plotting with Octave

    Plotting with Octave

Observe that both lines are parallel because they have the same slope. They have different y-intercepts (or y-value, an (x,y) point with x=0) so they are not coincident lines.

Plotting with Maxima

Plotting with Maxima

Graphs of Quadratic Functions

A quadratic function is a type of polynomial function. It has the form f(x) = ax2 + bx + c where a, b, and c are numbers with “a” not equal to zero. Its graph is a symmetric U-shaped curve called a parabola.

The quadratic formula provides the solution(s) to a quadratic equation:
x = -b ± √b2 -4*a*c2*a. The discriminant is the part of the quadratic formula underneath the square root symbol: b²-4ac. The discriminant tells us whether there are two solutions, one solution, or no solutions.

set terminal wxt size 400,250 enhanced font 'Verdana,11' persist
# Use set terminal to tell gnuplot what kind of output to generate. The wxt terminal device generates output in a separate window. 

set border linewidth 1.5 # set border controls the display of the graph borders for the plot and splot commands.

set style line 1 linecolor rgb '#0060ad' linetype 1 linewidth 2 # set style line defines a set of line types and widths and point types and sizes so that you can refer to them later by an index instead of repeating all the information at each invocation. 
set style line 2 linecolor rgb '#dddd1f' linetype 1 linewidth 2

set xzeroaxis linetype 3 linewidth 2 # It draws the x axis.
set xlabel 'x' # Set the label for the x-axis
set ylabel 'y' # Set the label for the y-axis
set yrange [-40:40]  The set yrange command sets the vertical range that will be displayed on the y axis. 
set xrange [-10:10] #  The set xrange command sets the horizontal range that will be displayed on the x axis. 

set key top left # The set key enables a key (or legend) describing plots on a plot. 
f(x)=-x**2-5*x+6 # We define two quadratic functions
g(x)=x**2+2*x+5
plot f(x) title '-x^2-5*x+6' with lines linestyle 1, \ # We plot f(x) using linestyle 1
     g(x) title 'x^2+2*x+5' with lines linestyle 2 # and g(x) using linestyle 2

Trigonometric functions

Trigonometric or circular functions are functions related to angles. The basic trigonometric functions include the following functions: sine (sin(x)), cosine (cos(x)), tangent (tan(x)), cotangent (cot(x)), secant (sec(x)) and cosecant (csc(x)).

An angle which is less than 90° is called an acute angle. Given a right triangle and an acute angle α in the triangle.
cos(α) = cos(33.69°) = the ratio of the length of the adjacent side of the angle divided by the length of the hypotenuse = 33.61 = 0.83.
sin(α) = sin(33.69°) = the ratio of the length of the opposite side of the angle divided by the length of the hypotenuse = 23.61 = 0.55.
tan(α) = tan(33.69°) = the ratio of the length of the opposite side of the angle divided by the length of the adjacent side = 23 = 0.66.
csc(α) = cos(33.69°) = the ratio of the hypotenuse to the opposite side, it is the reciprocal of the sine = 3.612 = 1.805.
sec(α) = sin(33.69°) = the ratio of the hypotenuse to the adjacent side, it is the reciprocal of the cosine = 3.613 = 1.20.
cotangent(α) = cot(33.69°) = the ratio of the adjacent side to the opposite side, it is the reciprocal of the tangent = 32 = 1.5. Trigonometric functions

Trigonometric functions

octave:1> x=-10:0.1:10; #  We use a x-vector to store the x-values: x=-10:0.1:10; (start -10:step 0.1:end 10, it defines a sequence from start to end by adding increments of step).
octave:2> y= sin(x); # Define our sin function. When plotting in Octave the plot points are required to have their x-values stored in one vector and the y-values in another vector.
octave:3> plot(x, y); # We use the command plot to plot functions in Octave
octave:4> title("Sin(x)") # We can add titles to an existing plot.
octave:5> xlabel("x") # We can add labels to an existing plot, too.
octave:6> ylabel("y")
octave:7> 
Trigonometric functions

Trigonometric functions

The tangent function has vertical asymptotes whenever cos(x)=0 (the function is undefined): -Pi⁄2, Pi⁄2, 3*Pi⁄2, etc.

Plotting more functions

The exponential function is the function f(x)=ex, where e = 2.71828… is Euler’s constant. More generally, an exponential function is a mathematical function of the following form: f(x)=abx where b is a positive real number (b > 0), b is not equal to 1 (b ≠ 1), and the argument x occurs as an exponent.

If b > 1, then the curve will be increasing and represent exponential growth. In other words, the values of the function get quickly very large. Notice that a larger base (b) makes the graph steeper. If 0 < b <1, then the curve will be decreasing and represent exponential decay. The function values “decay” or decrease as x values increase. They get closer and closer to 0. The exponential function

The exponential function

octave:1> x=-10:0.1:20; #  We use a x-vector to store the x-values: x=-10:0.1:10; (start -10:step 0.1:end 20, it defines a sequence from start to end by adding increments of step).
octave:2> clf; # clear the current figure window.
octave:3> plot(x, exp(x), 'r;Exponential;'); # We use the command plot to plot ex in Octave
octave:4> title("The exponential function") # We add a title

Plotting functions in Google is as easy as it gets. Observe that 2^x (b > 1) doubles every time when we add one to its input x (exponential growth). On the contrary, (1⁄2)^x (0 < b < 1) shrinks in half every time we add one to its input x (exponential decay). An exponential growth curve is rarely seen in nature. Exponential growth is not sustainable because it depends on infinite amounts of resources which do not exist in the real world.

The exponential function

The exponential function

The natural logarithm of x is the power to which e would have to be raised to equal x, e.g., ln 3.4 = 1.22377…, because e^1.22377… = 3.39998… It is the inverse function of the exponential function: elnx = x. It slowly grows to +∞ as x increases, and slowly grows to -∞ as x approaches 0, so the y-axis is a vertical asymptote.

In other words, the distance between the graph of the natural logarithm and x = 0 approaches zero as x gets closer to zero from the right.

The logarithm of a given number x is the exponent to which another fixed number, the base b, must be raised, to produce that very number x: logb(x) = y exactly if by = x. Let’s plot logarithmic functions with base e and other bases with wxMaxima.

log(x) represents the natural (base e) logarithm of x. However, Maxima does not have a built-in function for the base 10 logarithm or other bases. Do not worry my dear reader, for every problem there is a solution which is simple, clean and wrong -just joking.

We will use the change-of-base formula: logax = logbx⁄logba so the base-2 logarithm (also called the binary logarithm) is equal to the natural logarithm divided by log(2). Therefore, we could use log10(x):= log(x) / log(10); and log2(x):=log(x)/log(2); as useful definitions (radcan(log2(8)); = 3, radcan(expr); simplifies expr). Logarithm functions

Logarithm functions

We are going to plot |x|, √x, and sgn(x) using ZeGrapher, an open source, free, and easy to use math plotter. Install it, click on Windows, Functions or use the shortcut Ctrl + F, and type: sqrt(x) in the input box named “f(x)”, abs(x) in the input box named “g(x)”, and x/abs(x) in the input box named “h(x)”. Plotting with ZeGrapher

Plotting with ZeGrapher

A square root of a number x is a number “y” whose square is x: y2 = x. The domain of the square root function (y = sqrt(x)= √x) is all values of x such that x ≥ 0. The curve above looks like half of a parabola lying on its side.

The absolute value or modulus of x (it is represented by either abs(x) or |x| and read as “the absolute value of x”) is the non-negative value of x without regarding to its sign. It is its distance from zero on the number line. Namely, |x| = x if x is positive, |x| = −x if x is negative, and |0| = 0.

The sign of a real number, also called sgn or signum, is -1 for negative numbers, 0 for the number zero, or +1 for positive numbers. Any real number can be expressed as the product of its absolute value and its sign function: x=|x| * sgn(x), that’s why we use the formula x/abs(x) to plot it. It is an odd (the following equation holds for all x: -f(x) = f(-x)) mathematical function. Besides, it is not continuous at x = 0. Matplotlib

Matplotlib

Finally, we are going to plot the cube root using Matplotlib. The cube root of a number x is a number “y” that we multiply by itself three times to get x or, more formally, is a number y such that y3 = x. It is and odd function (its plot is symmetric with respect to the coordinate origin).

import numpy as np  # NumPy is a library for array computing with Python
import matplotlib.pyplot as plt  # Matplotlib is a plotting library for the Python programming language 
X = np.arange(-10, 10, 0.01) # Return evenly spaced numbers within the interval [-10, 10] as the values on the x axis.
def p(x): # This is the function that we are going to plot.
	return np.cbrt(x) # Return the cube-root of an array, element-wise.
F = p(X)  # The corresponding values on the y axis are stored in F.
plt.ylim([-4, 4]) # Set the y-limits on the current axes.
plt.plot(X, F, color='r') # These values x, y are plotted using the mathlib's plot() function.
plt.xlabel('x') # Set the label for the x-axis.
plt.ylabel('y') # Set the label for the y-axis.
plt.title('Cube root') # Set a title for the plot
plt.axvline(0) # Add a vertical line across the Axes
plt.axhline(0) # Add a horizontal line across the Axes
plt.show() # The graphical representation is displayed by using the show() function.

Piecewise-defined functions

A piecewise-defined function is a function defined by two or more sub-functions, where each sub-function applies to a different interval in the domain.

For example, the absolute value (|x| = -x if x < 0, |x| = x if x ≥ 0) and sign (sgn(x) = -1 if x < 0, sgn(x) = 0 if x = 0, sgn(x) = 1 if x > 0) functions are two examples of piecewise-defined functions.

Let’s plot a piecewise-defined function in Maxima. We are going to use Maxima’s command charfun(p); It returns 0 when the predicate p evaluates to false; and 1 when the predicate evaluates to true.

f(x):= charfun(x<2)*x^2 + charfun(x>=2)*4; is how we define piecewise-define functions in Maxima. For all values of x less than two, the first function (x2) is used. For all values of x greater than or equal to two, the second function (4) is used. Piecewise-defined functions

Piecewise-defined functions

Our function is continuous (it is continuous at every point in its domain; in other words, it does not have any abrupt changes in value -a function without breaks or gaps) because its constituent functions (x2, 4) are continuous on their corresponding intervals or subdomains ( -∞, 2), [2, +∞) and there is no discontinuity at 2.

Now we will plot another piecewise defined function with Octave: Piecewise-defined functions

Piecewise-defined functions

x=-5:0.01:-1; y=-x; plot(x,y, "linewidth", 4), hold on 
  1. We use a x-vector to store the x-values: x=-5:0.01:-1.
  2. Define our sub-function: y = -x for x in [-5, -1]
  3. Plot it.
  4. And hold on, so we ask Octave to retain plot data and settings so that subsequent plot commands are displayed on a single graph.
x=-1:0.01:0; y=x.^2; plot(x,y, "linewidth", 4), 

We define the sub-function: y = x2 for x in [-1, 0] and plot it. We set line width to 4.

x=0:0.01:5; y=sqrt(x); plot(x,y, "linewidth", 4)

We define the sub-function: y = √x for x in [0, 5] and plot it.

Piecewise-defined functions

Piecewise-defined functions

Finally, we will plot the following piecewise-defined function with Python using the library Mathplotlib. Piecewise-defined functions

Piecewise-defined functions

#!/usr/bin/env python
import numpy as np  # NumPy is a library for array computing with Python
import matplotlib.pyplot as plt # Matplotlib is a plotting library for the Python programming language 
import math

def piecewise (x): # This is our piecewise-defined function
    if x <= -1:
        return -x+2 
    elif -1 <= x <= 0:
        return pow(x, 2)
    else:
        return math.log(x) 

vpiecewise = np.vectorize(piecewise) # The purpose of np.vectorize is to transform functions which are not numpy-aware into functions that can operate on (and return) numpy arrays.

x = np.linspace(-5, 5, 10000) # Return evenly spaced numbers over [-5, 5] as the values on the x axis.  
y = vpiecewise(x) # Y values on the y axis.
plt.axvline(0)  # Add a vertical line across the Axes
plt.axhline(0)  # Add a horizontal line across the Axes
plt.plot(x, y, color='r')  # These values x, y are plotted using the mathlib's plot() function.
plt.show() # The graphical representation is displayed by using the show() function. The function is continuous at all points except where x=0.
Piecewise-defined functions

Piecewise-defined functions

Bitcoin donation

JustToThePoint Copyright © 2011 - 2022 Anawim. ALL RIGHTS RESERVED. Bilingual e-books, articles, and videos to help your child and your entire family succeed, develop a healthy lifestyle, and have a lot of fun.

This website uses cookies to improve your navigation experience.
By continuing, you are consenting to our use of cookies, in accordance with our Cookies Policy and Website Terms and Conditions of use.