Graphing Trigonometric Functions: How to Visualize the Beauty of Math (feat. Python)

In math class, did you ever try to draw graphs by hand when learning trigonometry? You can draw it roughly, but it's not always easy to make it look pretty, right? Now you can use Python to make it look exactly like that.

In this post, we'll show you how to easily and accurately plot graphs of the sin, cos, and tan functions using Python. We'll provide a step-by-step guide that even coding beginners can follow, plus tips for customizing your graphs. Mastering this skill will help you in your math assignments and data visualization projects.

Install the required libraries

First, you need to install the required libraries. Run the following command in your terminal Oh, by the way, if you don't know how to use VS code to run Python source code, Installing VS CODE - Windows Check out the post and follow along.

pip install numpy matplotlib

Writing basic code

Here is the basic code to plot graphs of the sin, cos, and tan functions.

# Import the numpy and matplotlib libraries.
import numpy as np
import matplotlib.pyplot as plt

# Generate 1000 uniformly spaced values of x from -2π to 2π.
x = np.linspace(-2 * np.pi, 2 * np.pi, 1000)

# Compute the values of the sin, cos, and tan functions for the generated x values.
y_sin = np.sin(x)
y_cos = np.cos(x)
y_tan = np.tan(x)

1Create a Figure object to plot the TP5T graph and set its size.
plt.figure(figsize=(12, 8))

Draw a graph of the # trigonometric function.
plt.plot(x, y_sin, label='sin(x)')
plt.plot(x, y_cos, label='cos(x)')
plt.plot(x, y_tan, label='tan(x)')
plt.legend()
plt.show()

If you try to plot a graph using the code above, you'll see something like this Each of the trigonometric functions is not properly identified, and the values on the x-axis are not what you would normally see (e.g., π).

삼각함수 그래프 그리기

Customizing graphs

Let's add some elements to the basic graph to make it look better:

# Import the numpy and matplotlib libraries.
import numpy as np
import matplotlib.pyplot as plt

# Generate 1000 uniformly spaced values of x from -2π to 2π.
x = np.linspace(-2 * np.pi, 2 * np.pi, 1000)

# Compute the values of the sin, cos, and tan functions for the generated x values.
y_sin = np.sin(x)
y_cos = np.cos(x)
y_tan = np.tan(x)

# Define a function to display a tick mark on the x-axis in π increments.
def set_pi_ticks(ax):
    # Sets the tick positions in π/2 intervals from -2π to 2π.
    ax.set_xticks(np.array(-2*np.pi, 2.1*np.pi, np.pi/2))
    # Set the label corresponding to each scale. Represent π in LaTeX format.
    ax.set_xticklabels([r'$-2\pi$', r'$-3\pi/2$', r'$-\pi$', r'$-\pi/2$', '0',
                        r'$\pi/2$', r'$\pi$', r'$3\pi/2$', r'$2\pi$'])

Set the size of the # graph (12 inches wide by 8 inches tall).
plt.figure(figsize=(12, 8))

# Get the current axis object.
ax = plt.gca()

# Plots graphs of the sin, cos, and tan functions. Each is displayed in a different color, and specify a name to appear in the legend.
plt.plot(x, y_sin, label='sin(x)')
plt.plot(x, y_cos, label='cos(x)')
plt.plot(x, y_tan, label='tan(x)')

Set a title for the # graph.
plt.title('Trigonometric Functions')

# Set the labels for the x and y axes.
plt.xlabel('x')
plt.ylabel('y')

# Draw the x-axis (y=0) and y-axis (x=0) as black solid lines.
plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)

Add gridlines to the # graph.
plt.grid(True)

Display the # legend.
plt.legend()

# Display a scale in π units on the x-axis.
set_pi_ticks(ax)

Limit the range of the # y-axis from -3 to 3.
plt.ylim(-3, 3)

# Automatically adjust the layout of the graph.
plt.tight_layout()

Display the # graph on the screen.
plt.show()
삼각함수 그래프 그리기

Drawing individual graphs

You can plot each function in a separate subplot to see it in more detail:

# Import the numpy and matplotlib libraries.
import numpy as np
import matplotlib.pyplot as plt

# Generate 1000 uniformly spaced values of x from -2π to 2π.
x = np.linspace(-2 * np.pi, 2 * np.pi, 1000)

# Compute the values of the sin, cos, and tan functions for the generated x values.
y_sin = np.sin(x)
y_cos = np.cos(x)
y_tan = np.tan(x)

# Define a function to display a tick mark on the x-axis in π increments.
def set_pi_ticks(ax):
    # Sets the tick positions in π/2 intervals from -2π to 2π.
    ax.set_xticks(np.array(-2*np.pi, 2.1*np.pi, np.pi/2))
    # Set the label corresponding to each scale. Represent π in LaTeX format.
    ax.set_xticklabels([r'$-2\pi$', r'$-3\pi/2$', r'$-\pi$', r'$-\pi/2$', '0',
                        r'$\pi/2$', r'$\pi$', r'$3\pi/2$', r'$2\pi$'])

# Set the size of the entire graph (12 inches wide by 12 inches tall).
plt.figure(figsize=(12, 12))

# Graph the sin function (first subplot)
ax1 = plt.subplot(3, 1, 1) # Create a subplot at the first position in the grid on row 3, column 1.
plt.plot(x, y_sin, label='sin(x)')  # Draw a graph of the sin function.
plt.title('Sin Function') # Set the title of the subplot.
plt.ylabel('sin(x)')  Set the # y-axis label.
plt.grid(True) # Adds grid lines.
plt.legend() # Displays a legend.
set_pi_ticks(ax1) # Shows a scale in π units on the x-axis.

# Graph the cos function (second subplot)
ax2 = plt.subplot(3, 1, 2) # Create a subplot at the second position in the grid on row 3, column 1.
plt.plot(x, y_cos, label='cos(x)', color='orange') # Plot the graph of the cos function in orange.
plt.title('Cos Function')
plt.ylabel('cos(x)')
plt.grid(True)
plt.legend()
set_pi_ticks(ax2)

Graph the # tan function (third subplot)
ax3 = plt.subplot(3, 1, 3) # Create a subplot at the third position in the grid on row 3, column 1.
plt.plot(x, y_tan, label='tan(x)', color='green') # Plot the graph of the tan function in green.
plt.title('Tan Function')
plt.xlabel('x') # Set the x-axis label (only visible on the bottom subplot).
plt.ylabel('tan(x)')
plt.ylim(-10, 10) # Limit the range of the y-axis from -10 to 10 (to account for the divergence of the tan function).
plt.grid(True)
plt.legend()
set_pi_ticks(ax3)

Automatically adjust the spacing between the # subplots.
plt.tight_layout()

Display the # graph on the screen.
plt.show()
삼각함수 그래프 그리기

Organize

In this post, we've seen how to easily visualize complex mathematical functions using Python and Matplotlib. Applying these techniques will make it easier to understand and explain various mathematical concepts.

Try graphing some more extended functions, like sin(2x). You'll get a better feel for these graphs than you would in your head! Just Try it!

Similar Posts