Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to plot in matplotlib

Understanding the Basics of Plotting with Matplotlib

When you're just starting to learn programming, creating visual representations of data can be a thrilling experience. Think of it as translating numbers and data points into a visual story that anyone can understand at a glance. Matplotlib is a popular library in Python used for this very purpose. In simple terms, it's a tool that lets you create a wide variety of graphs and plots.

Setting Up Your Canvas: The Plotting Area

Before we start drawing, we need a canvas. In Matplotlib, this canvas is called a figure. You can think of a figure as a blank piece of paper where you'll draw your graphs. Here's how you can create one:

import matplotlib.pyplot as plt

# This creates a new figure (canvas) to draw on
fig = plt.figure()

Drawing Your First Line Plot

Let's start with something simple: a line plot. Imagine you're drawing a line that represents your walk from home to a park. Your horizontal steps could represent time, and your vertical steps could represent distance.

Here's how you can create a basic line plot with some example data:

# Sample data
time = [0, 1, 2, 3, 4]  # Time in hours
distance = [0, 1, 2, 3, 4]  # Distance in kilometers

# Plotting the data
plt.plot(time, distance)

# Showing the plot
plt.show()

When you run this code, you'll see a nice diagonal line going up, representing that as time increases, so does the distance.

Adding a Touch of Style: Titles and Labels

Your plot is like a book; it needs a title and labels to be understood correctly. The title tells you what the story is about, and the labels are like the names of different chapters, explaining what each axis represents.

# Plotting the data
plt.plot(time, distance)

# Adding a title
plt.title('My Walk to the Park')

# Adding labels
plt.xlabel('Time (hours)')
plt.ylabel('Distance (km)')

# Showing the plot
plt.show()

Now when you look at the plot, you'll know immediately that it's about a walk to the park, measured in time and distance.

Exploring Different Types of Plots

The Scatter Plot: A Starry Night Sky

Imagine looking up at the night sky and seeing stars scattered about. Each star's position tells you a story. A scatter plot is similar; it shows individual data points scattered across your plot.

Here's how you create a scatter plot:

# Sample data
temperatures = [22, 25, 28, 18, 30]  # Temperatures in degrees Celsius
ice_cream_sales = [15, 25, 35, 10, 45]  # Ice cream sales

# Creating a scatter plot
plt.scatter(temperatures, ice_cream_sales)

# Titles and labels
plt.title('Ice Cream Sales vs. Temperature')
plt.xlabel('Temperature (Celsius)')
plt.ylabel('Ice Cream Sales')

# Showing the plot
plt.show()

Each dot on the plot is like a star, showing you the relationship between temperature and ice cream sales.

The Bar Chart: A City's Skyline

A bar chart is like a city skyline, where each building represents a different category and its height tells you something about that category.

Let's plot a bar chart:

# Sample data
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 30]

# Creating a bar chart
plt.bar(categories, values)

# Titles and labels
plt.title('Category Values')
plt.xlabel('Categories')
plt.ylabel('Values')

# Showing the plot
plt.show()

Each bar is like a building, with its height showing the value for each category.

Customizing Your Plots

Colors and Styles: Dressing Up Your Plot

Just like choosing an outfit, you can customize the colors and styles of your plots to make them more appealing or to convey different meanings.

# Customizing the line plot
plt.plot(time, distance, color='green', linestyle='--', marker='o')

# Titles and labels
plt.title('My Stylish Walk to the Park')
plt.xlabel('Time (hours)')
plt.ylabel('Distance (km)')

# Showing the plot
plt.show()

Now your plot has a green dashed line with circular markers at each data point, making it more distinctive.

Legends: The Key to Your Plot's Story

When you have multiple lines or elements in a plot, a legend acts as a guide, telling you what each element represents.

# Two sets of data
time = [0, 1, 2, 3, 4]
distance_walk = [0, 1, 2, 3, 4]
distance_bike = [0, 2, 4, 6, 8]

# Plotting both sets of data
plt.plot(time, distance_walk, label='Walk')
plt.plot(time, distance_bike, label='Bike')

# Adding a legend
plt.legend()

# Titles and labels
plt.title('My Commute to the Park')
plt.xlabel('Time (hours)')
plt.ylabel('Distance (km)')

# Showing the plot
plt.show()

The legend tells the viewer that one line represents walking and the other biking.

Saving Your Masterpiece

After creating your plot, you might want to save it to show it to others or include it in a presentation. Here's how you do it:

# Plot your data here (refer to previous examples)

# Save the figure
plt.savefig('my_plot.png')

This saves your plot as an image file called 'my_plot.png' on your computer.

Conclusion: The Art of Storytelling with Data

Congratulations! You've just begun your journey into the world of data visualization with Matplotlib. Like an artist with a palette of colors and brushes, you now have the tools to tell visual stories with data. Remember, a plot is not just a bunch of lines and points; it's a narrative. With each graph you create, you're sharing insights and stories hidden within the numbers. Keep practicing, experimenting with different plot types, and customizing your creations to become a master storyteller of the data realm. Happy plotting!