Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to plot in Python

Introduction to Plotting in Python

Welcome to the world of Python programming, where the possibilities are endless! Today, we will learn about plotting in Python, which is one of the essential tools for anyone learning programming, especially for data visualization.

Plotting is the process of creating graphs or charts to represent data visually. It helps us understand the data better and find patterns, trends, or any unusual behavior in the data. In this blog post, we will go through the basics of plotting in Python, different libraries available for plotting, and how to create some simple plots using examples.

Before we dive in, let's take a moment to explain some jargon that might come up later in this post:

Library: A collection of pre-written code that you can use in your projects. Think of it as a set of tools that someone else created for you to use.

Package: A collection of Python modules, which are individual files containing Python code. A package is a way to organize and distribute these modules.

Function: A block of reusable code that performs a specific task. You can call a function with some input data (also known as arguments), and it will return an output based on the input.

Axis: The horizontal or vertical line in a chart, used to represent the scale and labels of the data.

Plotting Libraries in Python

There are many libraries available in Python for creating plots. Some of the popular ones are:

Matplotlib: A widely-used library that allows you to create static, interactive, and animated visualizations in Python. It is particularly useful for creating simple 2D plots.

Seaborn: A library based on Matplotlib that provides a high-level interface for creating statistical graphics. It comes with several built-in themes and color palettes to make it easy to create aesthetically pleasing visualizations.

Plotly: A library for creating interactive and web-based visualizations in Python. It supports a wide range of chart types, including scatter plots, bar charts, line charts, and more.

Bokeh: Another library for creating interactive and web-based visualizations, similar to Plotly. Bokeh focuses on providing more control over the look and feel of the visualizations.

For this blog post, we will primarily focus on using Matplotlib, as it is the most popular and widely-used library for plotting in Python.

Getting Started with Matplotlib

Before we can start using Matplotlib, we need to install it. You can install the Matplotlib package using the following command:

pip install matplotlib

Once the installation is complete, you can import it into your Python script using the following line of code:

import matplotlib.pyplot as plt

Now that we have Matplotlib installed and imported, let's create our first plot!

Creating a Simple Line Plot

A line plot is a type of chart that displays information as a series of data points connected by straight line segments. It is often used to represent the trend of a variable over time or the relationship between two variables.

Let's create a simple line plot of the following data:

  • Time (in hours): 0, 1, 2, 3, 4, 5
  • Temperature (in Celsius): 20, 21, 22, 23, 24, 25

To create a line plot, we can use the plt.plot() function provided by Matplotlib. The function takes two lists as input: the x-axis values and the y-axis values. Here's the code to create our line plot:

# Data for plotting
time = [0, 1, 2, 3, 4, 5]
temperature = [20, 21, 22, 23, 24, 25]

# Create a line plot
plt.plot(time, temperature)

# Add a title and labels to the axes
plt.title("Temperature vs Time")
plt.xlabel("Time (hours)")
plt.ylabel("Temperature (Celsius)")

# Display the plot
plt.show()

This code will create a line plot of the temperature vs time data, add a title and axis labels, and display the plot. The result should look like this:

Line plot example

Now that we've created our first plot let's explore some other types of plots and how to create them.

Creating a Bar Chart

A bar chart is a type of chart that presents categorical data with rectangular bars with heights or lengths proportional to the values that they represent. Bar charts can be used to compare values across different categories or groups.

Let's create a simple bar chart to display the number of items sold for different products in a store:

  • Products: A, B, C, D, E
  • Items Sold: 50, 30, 45, 25, 60

To create a bar chart, we can use the plt.bar() function provided by Matplotlib. The function takes two lists as input: the x-axis values (categories) and the y-axis values (numeric values). Here's the code to create our bar chart:

# Data for plotting
products = ['A', 'B', 'C', 'D', 'E']
items_sold = [50, 30, 45, 25, 60]

# Create a bar chart
plt.bar(products, items_sold)

# Add a title and labels to the axes
plt.title("Items Sold by Product")
plt.xlabel("Product")
plt.ylabel("Items Sold")

# Display the plot
plt.show()

This code will create a bar chart of the items sold by product data, add a title and axis labels, and display the plot. The result should look like this:

Bar chart example

Creating a Scatter Plot

A scatter plot is a type of chart that displays values for two variables as a set of points in a coordinate plane. It is often used to explore the relationship or correlation between two variables.

Let's create a simple scatter plot to display the relationship between the weight and height of a group of people:

  • Weight (in kg): [65, 50, 75, 80, 60, 55, 70, 68, 62, 58]
  • Height (in cm): [170, 150, 180, 190, 160, 155, 175, 172, 168, 162]

To create a scatter plot, we can use the plt.scatter() function provided by Matplotlib. The function takes two lists as input: the x-axis values (first variable) and the y-axis values (second variable). Here's the code to create our scatter plot:

# Data for plotting
weight = [65, 50, 75, 80, 60, 55, 70, 68, 62, 58]
height = [170, 150, 180, 190, 160, 155, 175, 172, 168, 162]

# Create a scatter plot
plt.scatter(weight, height)

# Add a title and labels to the axes
plt.title("Weight vs Height")
plt.xlabel("Weight (kg)")
plt.ylabel("Height (cm)")

# Display the plot
plt.show()

This code will create a scatter plot of the weight vs height data, add a title and axis labels, and display the plot. The result should look like this:

Scatter plot example

Customizing Plots

Matplotlib provides many options to customize the appearance of your plots, such as changing the colors, adding markers, or adjusting the line style. Let's customize our previous line plot of temperature vs time to make it more visually appealing.

Here's the code to create a customized line plot:

# Data for plotting
time = [0, 1, 2, 3, 4, 5]
temperature = [20, 21, 22, 23, 24, 25]

# Create a line plot with customizations
plt.plot(time, temperature, color='red', linestyle='dashed', marker='o', markersize=8)

# Add a title and labels to the axes
plt.title("Temperature vs Time")
plt.xlabel("Time (hours)")
plt.ylabel("Temperature (Celsius)")

# Display the plot
plt.show()

In this code, we've added the following customizations to the plt.plot() function:

  • color='red': Changes the color of the line to red.
  • linestyle='dashed': Changes the line style to dashed.
  • marker='o': Adds circular markers to the data points.
  • markersize=8: Sets the size of the markers to 8.

The resulting customized line plot should look like this:

Customized line plot example

Feel free to explore the Matplotlib documentation for more customization options and other types of plots.

Conclusion

In this blog post, we've learned the basics of plotting in Python using the Matplotlib library. We've covered how to create simple line plots, bar charts, and scatter plots, as well as customizing the appearance of these plots.

Keep in mind that this is just the tip of the iceberg when it comes to plotting in Python. There are many more types of plots and customization options available, as well as other libraries like Seaborn, Plotly, and Bokeh that offer even more advanced visualization capabilities.

As you continue your programming journey, don't be afraid to experiment, explore, and create your own visual masterpieces using Python's powerful plotting libraries. Happy plotting!