Skip to main content
Mathematics LibreTexts

1.3: Plotting

  • Page ID
    122062
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    There are several packages for plotting functions and we will use the PyPlot package. Similar to the NumPy package, we must import the PyPlot package before we use it. We will use the alias plt. The first time you import PyPlot during a session, it will need to automatically download the package and install the dependencies.

    import matplotlib.pyplot as plt
    

    output:

    To actually plot a graph, we will also call the NumPy package so that we have access to the sin function.

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.linspace(0, 2*np.pi, 1000)
    y = np.sin(3*x)
    plt.plot(x, y, color='red', linewidth=2.0, linestyle='--')
    plt.title('The sine function');
    plt.show()
    

    output:

    clipboard_e3c98195c3f2ad8aaebb8058dc7e22990.png

    Observe that, in the code above, we define the x-values we desire to be plotted using NumPy's linspace function. This function returns evenly spaced numbers over a specified interval. Here, we called for 1000 evenly-spaced numbers between 0 and \(2pi\). Then, we defined the y-values as a function of x. Here, we used \(y=\sin(3x)\).

    In the following example, we plot two functions, \(\sin(3x)\) and \(\cos(x)\) simultaneously.

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.linspace(0, 2*np.pi, 1000)
    y = np.sin(3*x)
    z = np.cos(x)
    plt.plot(x, y, color='red', linewidth=2.0, linestyle='--', label='sin(3x)')
    plt.plot(x, z, color='blue', linewidth=1.0, linestyle='-', label='cos(x)')
    plt.legend(loc='upper center');
    plt.show()
    

    output:

    clipboard_ee5fb4ea9f012d39abcd918e83e0f505a.png


    1.3: Plotting is shared under a not declared license and was authored, remixed, and/or curated by LibreTexts.

    • Was this article helpful?