Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to plot function in matplotlib

Understanding Matplotlib

Before we dive into plotting functions, let's briefly understand what Matplotlib is. Matplotlib is a plotting library in Python that allows you to create a wide variety of static, animated, and interactive visualizations. Think of it as a magical canvas where you can paint graphs and charts with data.

Setting Up Your Environment

To start plotting, you need to have Matplotlib installed. If you haven't installed it yet, you can do so by running the following command in your terminal or command prompt:

pip install matplotlib

Also, ensure you have Python installed on your computer. Python is the language we will be using to write our plotting scripts.

Starting with a Simple Plot

Let's begin with a simple example. We will plot a straight line. In the world of mathematics, a straight line can be represented by the equation y = mx + c, where m is the slope and c is the y-intercept.

Here’s how we can plot this in Python using Matplotlib:

import matplotlib.pyplot as plt

# Define the slope (m) and y-intercept (c)
m = 1
c = 0

# Generate a list of x values
x_values = range(-10, 11)  # This will give us a list from -10 to 10

# Calculate the y values based on the straight line equation
y_values = [m*x + c for x in x_values]

# Plot the line
plt.plot(x_values, y_values)

# Show the plot
plt.show()

When you run this script, you should see a straight line crossing through the origin (0,0).

Plotting Mathematical Functions

Now, let's plot something a bit more complex—a quadratic function. A quadratic function can be written as y = ax^2 + bx + c. It forms a parabola when plotted.

import matplotlib.pyplot as plt

# Define the coefficients a, b, and c
a = 1
b = 0
c = 0

# Generate a list of x values
x_values = range(-10, 11)

# Calculate the y values based on the quadratic equation
y_values = [a*x**2 + b*x + c for x in x_values]

# Plot the parabola
plt.plot(x_values, y_values)

# Show the plot
plt.show()

When you run this code, you should see a U-shaped parabola.

Customizing Your Plots

Matplotlib allows you to customize plots in many ways—changing colors, adding labels, and much more. Let's customize our quadratic function plot:

import matplotlib.pyplot as plt

a, b, c = 1, 0, 0
x_values = range(-100, 101)
y_values = [a*x**2 + b*x + c for x in x_values]

# Plot the parabola with a red dashed line
plt.plot(x_values, y_values, 'r--')

# Add a title and labels to the axes
plt.title('Quadratic Function')
plt.xlabel('x values')
plt.ylabel('y values')

# Add a grid for better readability
plt.grid(True)

# Show the plot
plt.show()

Here, 'r--' tells Matplotlib to plot a red (r) dashed line (--). The plt.title, plt.xlabel, and plt.ylabel functions add a title and labels to the axes, respectively. plt.grid(True) adds a grid.

Plotting Multiple Functions on the Same Graph

Sometimes you might want to compare different functions by plotting them on the same graph. Here's how to do that:

import matplotlib.pyplot as plt

# Define our x values
x_values = range(-10, 11)

# Define multiple functions
def linear_function(x):
    return x

def quadratic_function(x):
    return x**2

def cubic_function(x):
    return x**3

# Calculate y values for each function
y_linear = [linear_function(x) for x in x_values]
y_quadratic = [quadratic_function(x) for x in x_values]
y_cubic = [cubic_function(x) for x in x_values]

# Plot each function with different styles
plt.plot(x_values, y_linear, label='Linear')
plt.plot(x_values, y_quadratic, 'r--', label='Quadratic')
plt.plot(x_values, y_cubic, 'g-.', label='Cubic')

# Add a legend to explain which line is which
plt.legend()

# Show the plot
plt.show()

The label parameter in the plt.plot function is used to label each line, and plt.legend() displays a legend on the plot.

Understanding Axes and Figures

In Matplotlib, the entire window is called a Figure, and each graph you plot is called an Axes. If you want to plot multiple graphs in one window, you can do so by creating subplots.

import matplotlib.pyplot as plt

# Create a figure and a set of subplots
fig, axs = plt.subplots(2)

# Plot a linear function on the first subplot
axs[0].plot(x_values, y_linear, 'b-')
axs[0].set_title('Linear Function')

# Plot a quadratic function on the second subplot
axs[1].plot(x_values, y_quadratic, 'r--')
axs[1].set_title('Quadratic Function')

# Automatically adjust the subplot params for better layout
plt.tight_layout()

# Show the plot
plt.show()

Saving Your Plots

After creating a plot, you might want to save it to a file. You can do this with the savefig function.

plt.plot(x_values, y_quadratic, 'r--')
plt.title('Quadratic Function')
plt.xlabel('x values')
plt.ylabel('y values')
plt.grid(True)

# Save the figure to a file
plt.savefig('quadratic_function.png')

# Show the plot
plt.show()

This will save the plot as a PNG file in the current working directory.

Conclusion

Matplotlib is like a Swiss Army knife for plotting in Python—it's versatile, powerful, and can handle most of your plotting needs. By understanding the basics of plotting functions, customizing your plots, and managing multiple graphs, you're now well-equipped to visualize mathematical functions and data.

Remember, practice is key. Don't hesitate to experiment with different types of plots and customizations. Each graph tells a story, and with Matplotlib, you're the author, ready to illustrate the tales hidden within your data. Happy plotting!