Back to Python
2026-02-115 min read

Matplotlib Pyplot (Python Programming)

Learn Matplotlib Pyplot (Python Programming) step by step with clear examples and exercises.

Title: Matplotlib Pyplot Tutorial (Python Programming)

Why This Matters

Mastering Matplotlib, a popular Python library for data visualization, is essential as it enables you to create engaging and informative plots that help make your data more accessible. In interviews, understanding Matplotlib can demonstrate your problem-solving skills and ability to work with complex datasets.

Prerequisites

Before diving into Matplotlib, ensure you have a solid grasp of Python syntax and basic concepts such as variables, functions, lists, control structures (if, for, while), and familiarity with NumPy is beneficial but not necessary.

Core Concept

Matplotlib Pyplot provides an object-oriented interface to create various types of plots using Python. To get started, import the matplotlib library and use its pyplot submodule:

import matplotlib.pyplot as plt

Creating a Simple Plot

To create a simple plot, call the plot() function with your data as arguments. This example creates a line graph of y = x²:

x = list(range(10)) # Generate numbers from 0 to 9 (inclusive)
y = [i**2 for i in x] # Calculate the square of each number in the x range
plt.plot(x, y) # Add the line graph to the current figure
plt.show() # Display the plot

In this code snippet:

  • The range() function generates a list of numbers from 0 to 9 (inclusive).
  • A list comprehension calculates the square of each number in the x range.
  • plt.plot(x, y) adds the line graph to the current figure.
  • plt.show() displays the plot.

Customizing Your Plot

Matplotlib offers numerous options for customizing your plots. Some common modifications include:

  1. Changing the title and labels with plt.title(), plt.xlabel(), and plt.ylabel()
  2. Setting plot limits using plt.xlim() and plt.ylim()
  3. Adjusting the line style, color, and marker with plt.style.use(), plt.plot_params(), and plt.scatter()
  4. Modifying gridlines using plt.grid(True/False) or customizing them with plt.grid(which='major' | 'minor', linestyle, linewidth, color)
  5. Adding legends using plt.legend(labels)
  6. Saving the plot as an image file using plt.savefig('filename.ext')
  7. Creating multiple subplots with plt.subplot(), plt.subplot2grid(), or plt.figure()

Worked Example

Let's create a bar graph comparing the population of the top five most populous countries in 2021:

import matplotlib.pyplot as plt

populations = {
'China': 1439323776,
'India': 1380004385,
'United States': 331002651,
'Indonesia': 273523615,
'Pakistan': 220987570
}

countries = list(populations.keys())
populations_list = list(populations.values())

fig, ax = plt.subplots() # Create a figure and an axis for the plot
ax.bar(countries, populations_list) # Add the bar graph to the current axis
ax.set_title('World Population in 2021') # Set the plot title
ax.set_xlabel('Country') # Set the x-axis label
ax.set_ylabel('Population (millions)') # Set the y-axis label
plt.show() # Display the plot

In this example:

  • A dictionary stores the population data for each country.
  • The keys and values are extracted as separate lists.
  • We create a figure and an axis using plt.subplots().
  • ax.bar(countries, populations_list) creates a bar graph with countries on the x-axis and populations on the y-axis.
  • Additional calls to ax.set_title(), ax.set_xlabel(), and ax.set_ylabel() set the plot title and axis labels.

Common Mistakes

  1. Forgetting to call plt.show(): Remember that Matplotlib plots are not automatically displayed; you must call plt.show() to see your graph.
  2. Not setting x and y limits: If your data has a large range, it can cause the plot to become cluttered or difficult to read. Use plt.xlim() and plt.ylim() to set appropriate axis limits.
  3. Not labeling axes: Labels help others understand your plot more easily. Include a title and labels for both the x-axis and y-axis.
  4. Using incorrect data types: Matplotlib functions expect specific data types (lists, arrays, etc.). Ensure that you are passing appropriate data to each function.
  5. Not closing the plot window: When working with multiple plots, remember to call plt.close() before creating a new one to avoid cluttering your workspace.
  6. ### Incorrectly handling missing or negative data:
  • Use numpy.nan for missing values and handle them appropriately in your plotting functions.
  • For negative data, consider using line plots with markers (e.g., plt.plot(x, y, 'o')) to distinguish them from positive data points.
  1. ### Ignoring error messages:
  • Pay attention to error messages and understand their meaning to help you troubleshoot issues.
  1. ### Overcomplicating plots:
  • Keep your plots simple and easy to understand, focusing on the key insights you want to convey.
  1. ### Not using appropriate plot types for different data:
  • Use line plots for trend analysis, bar graphs for comparing categorical data, scatter plots for examining relationships between two variables, etc.

Practice Questions

  1. Create a scatter plot of the relationship between height and weight for 10 randomly generated data points.
  2. Create a histogram of the number of vowels in each word from a list of 50 English words.
  3. Modify the bar graph example to display the top ten most populous countries, sorted in descending order by population.
  4. Create a line plot of the function y = x³ for x values between -10 and 10.
  5. Create a box plot comparing the average height of men and women from different countries.
  6. Create a heatmap to visualize the correlation matrix of a dataset containing multiple variables.
  7. Create a 3D scatter plot of the relationship between three variables (x, y, z) using Matplotlib's mplot3d module.
  8. Create a polar plot to represent the distribution of angles in a dataset.
  9. Use Matplotlib's animation API to create an animated plot showing how a function changes over time.
  10. Create a log-log plot to visualize data with a power-law relationship between two variables.

FAQ

How do I create a pie chart with Matplotlib Pyplot?

A: Use the pie() function to create a pie chart. For example, to create a pie chart of the population data from the worked example:

populations_list = list(populations.values())
labels = list(populations.keys())
fig, ax = plt.subplots() # Create a figure and an axis for the plot
ax.pie(populations_list, labels=labels) # Add the pie chart to the current axis
plt.show() # Display the plot

How can I save my Matplotlib plot as an image file?

A: To save your plot as a PNG image file, use the savefig() function:

fig, ax = plt.subplots() # Create a figure and an axis for the plot
ax.pie(populations_list, labels=labels) # Add the pie chart to the current axis
fig.savefig('world_population.png') # Save the plot as a PNG image file
plt.show() # Display the plot

This will save the current plot as a PNG image file named world_population.png. You can change the filename and file format by modifying the arguments passed to savefig().

Matplotlib Pyplot (Python Programming) | Python | XQA Learn