Matplotlib in Python: A Complete Guide

Sun Sep 08 2024

Matplotlib library

Matplotlib Intro

What is Matplotlib?

Matplotlib is a light and practical Python library. It displays line graphs, bar charts, scatter plots, and histograms among others. It just makes it so much easier to show visually the trends or patterns in your data that would not be that obvious without visualizing it. You can also use Matplotlib along with other libraries like NumPy and Pandas, thus, it is really useful in data analysis tasks. Whether one is comparing categories or tracking changes over time, Matplotlib has the means at hand for making data far clearer and understandable.
Have you tried using Matplotlib to explore your data? How could charts and graphs help you spot patterns or make better decisions? Give it a try! That may be all that you need to make the analysis of data simpler and more effective.

Where is the Matplotlib Codebase?

The Matplotlib codebase is open-source and can be found on GitHub. You can explore it for issues, pull requests, and contributions.

Matplotlib Getting Started

Installation of Matplotlib

To get started with Matplotlib, you first need to install it using pip:

python
1pip install matplotlib

Import Matplotlib

Once installed, you can import the pyplot module, which is used for most of the plotting functions:

python
1import matplotlib.pyplot as plt

Checking Matplotlib Version

It's good practice to check the version of Matplotlib you're using. You can do this using:

python
1import matplotlib
2print(matplotlib.__version__)

Matplotlib Pyplot

What is Pyplot?

Pyplot is a submodule of Matplotlib that provides a MATLAB-like interface for making plots. You can easily create plots, add labels, titles, and customize them.

Matplotlib Plotting

Plotting x and y points

To plot x and y points on a graph, you can use the plot() function:

python
1import matplotlib.pyplot as plt
2
3x = [1, 2, 3, 4]
4y = [1, 4, 9, 16]
5
6plt.plot(x, y)
7plt.show()

This will generate a simple line plot connecting the points (1, 1), (2, 4), (3, 9), and (4, 16).

Plotting Without Line

If you want to plot just the points without connecting them with a line, you can use the 'o' marker:

python
1plt.plot(x, y, 'o')
2plt.show()

Multiple Points

You can plot multiple sets of points on the same graph:

python
1x1 = [1, 2, 3, 4]
2y1 = [1, 4, 9, 16]
3
4x2 = [1, 2, 3, 4]
5y2 = [2, 4, 6, 8]
6
7plt.plot(x1, y1, 'o')
8plt.plot(x2, y2)
9plt.show()

Default X-Points

If you only provide y-values, Matplotlib assumes the x-values are the indices of the array:

python
1y = [1, 4, 9, 16]
2plt.plot(y)
3plt.show()

Matplotlib Markers

Marker Reference

You can change the appearance of the markers in your plot using various marker styles. For example, you can use 'o', '^', or 's' for circle, triangle, and square markers:

python
1plt.plot(x, y, marker='^')
2plt.show()

Format Strings (fmt)

In Matplotlib, you can define the format of the line using a format string (fmt):

python
1plt.plot(x, y, 'ro')  # Red circles
2plt.show()

Line Reference

You can customize the line style by specifying the linestyle argument:

python
1plt.plot(x, y, linestyle='--')  # Dashed line
2plt.show()

Color Reference

To change the line color, you can specify the color argument:

python
1plt.plot(x, y, color='green')
2plt.show()

Marker Size

You can adjust the size of the marker using the markersize argument:

python
1plt.plot(x, y, marker='o', markersize=10)
2plt.show()

Marker Color

To change the color of the marker, use the markerfacecolor argument:

python
1plt.plot(x, y, marker='o', markersize=10, markerfacecolor='blue')
2plt.show()

Matplotlib Line

Linestyle

You can define different line styles for your plot, such as dashed (--), dotted (:), or solid (-):

python
1plt.plot(x, y, linestyle=':')
2plt.show()

Shorter Syntax

You can combine color, marker, and line style in a short format:

python
1plt.plot(x, y, 'g^--')  # Green triangles with dashed line
2plt.show()

Line Styles

Matplotlib supports different line styles, such as '-' for solid, '--' for dashed, and '-.' for dash-dot:

python
1plt.plot(x, y, linestyle='-.')
2plt.show()

Line Color

You can easily customize the line color:

python
1plt.plot(x, y, color='purple')
2plt.show()

Multiple Lines

You can plot multiple lines on the same graph by calling plot() multiple times:

python
1plt.plot(x1, y1, label="Line 1")
2plt.plot(x2, y2, label="Line 2")
3plt.legend()
4plt.show()

Matplotlib Labels and Title

Create Labels for a Plot

You can add labels to the x-axis and y-axis using xlabel() and ylabel():

python
1plt.plot(x, y)
2plt.xlabel("X Axis")
3plt.ylabel("Y Axis")
4plt.show()

Create a Title for a Plot

You can add a title to the plot using the title() function:

python
1plt.plot(x, y)
2plt.title("Sample Plot")
3plt.show()

Set Font Properties for Title and Labels

You can customize the font of the title and labels using the fontdict parameter:

python
1plt.plot(x, y)
2plt.title("Custom Title", fontdict={'fontsize': 14, 'fontweight': 'bold'})
3plt.xlabel("X Axis", fontdict={'fontsize': 12})
4plt.ylabel("Y Axis", fontdict={'fontsize': 12})
5plt.show()

Matplotlib Adding Grid Lines

Add Grid Lines to a Plot

You can add grid lines to your plot using the grid() function:

python
1plt.plot(x, y)
2plt.grid(True)
3plt.show()

Specify Which Grid Lines to Display

You can control whether to show grid lines on the x-axis or y-axis:

python
1plt.plot(x, y)
2plt.grid(axis='y')  # Only grid on y-axis
3plt.show()

Set Line Properties for the Grid

You can customize the appearance of the grid lines:

python
1plt.plot(x, y)
2plt.grid(color='gray', linestyle='--', linewidth=0.5)
3plt.show()

Matplotlib Subplot

Display Multiple Plots

With Matplotlib subplots, you can display multiple plots in one figure using the subplot() function:

python
1plt.subplot(1, 2, 1)  # 1 row, 2 columns, position 1
2plt.plot(x, y)
3
4plt.subplot(1, 2, 2)  # 1 row, 2 columns, position 2
5plt.plot(x, y2)
6
7plt.show()

The subplot() Function

The subplot() function allows you to specify the number of rows, columns, and the current plot position in the figure.

Title and Super Title

You can give each subplot its own title, and also add a main title using suptitle():

python
1plt.subplot(1, 2, 1)
2plt.plot(x, y)
3plt.title("First Plot")
4
5plt.subplot(1, 2, 2)
6plt.plot(x, y2)
7plt.title("Second Plot")
8
9plt.suptitle("Main Title")
10plt.show()

Matplotlib Scatter

Creating Scatter Plots

To create a scatter plot, use the scatter() function:

python
1plt.scatter(x, y)
2plt.show()

Compare Plots

You can plot scatter plots and line plots together for comparison:

python
1plt.plot(x, y, label="Line")
2plt.scatter(x, y2, color='red', label="Scatter")
3plt.legend()
4plt.show()

Colors

You can specify colors for scatter plot points:

python
1plt.scatter(x, y, color='green')
2plt.show()

Color Each Dot

You can assign different colors to each dot in the scatter plot:

python
1colors = ['red', 'blue', 'green', 'orange']
2plt.scatter(x, y, c=colors)
3plt.show()

ColorMap

You can apply a colormap to your scatter plot:

python
1import numpy as np
2
3x = np.random.rand(50)
4y = np.random.rand(50)
5colors = np.random.rand(50)
6
7plt.scatter(x, y, c=colors, cmap='viridis')
8plt.colorbar()
9plt.show()

Size

You can specify the size of each point in the scatter plot:

python
1sizes = [20, 50, 100, 200]
2plt.scatter(x, y, s=sizes)
3plt.show()

Alpha

You can control the transparency of the points using the alpha argument:

python
1plt.scatter(x, y, alpha=0.5)
2plt.show()

Combine Color, Size, and Alpha

You can combine color, size, and transparency in a single scatter plot:

python
1sizes = 1000 * np.random.rand(50)
2alpha = 0.5
3
4plt.scatter(x, y, c=colors, s=sizes, alpha=alpha, cmap='plasma')
5plt.colorbar()
6plt.show()

Matplotlib Bars

Creating Bars

To create a bar chart, use the bar() function:

python
1x = ['A', 'B', 'C', 'D']
2y = [3, 8, 1, 10]
3
4plt.bar(x, y)
5plt.show()

Bar Color

You can change the color of the bars:

python
1plt.bar(x, y, color='orange')
2plt.show()

Color Names and Hex Codes

You can use color names or hexadecimal color codes:

python
1plt.bar(x, y, color='#4CAF50')  # Hex color
2plt.show()

Bar Width and Height

You can adjust the width of the bars using the width argument:

python
1plt.bar(x, y, width=0.4)
2plt.show()

Matplotlib Histograms

Creating Histograms

To create a histogram, use the hist() function:

python
1data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
2
3plt.hist(data, bins=4)
4plt.show()

Matplotlib Pie Charts

Creating Pie Charts

You can create a pie chart using the pie() function:

python
1labels = ['A', 'B', 'C', 'D']
2sizes = [15, 30, 45, 10]
3
4plt.pie(sizes, labels=labels)
5plt.show()

Labels and Start Angle

You can add labels and change the starting angle of the pie chart:

python
1plt.pie(sizes, labels=labels, startangle=90)
2plt.show()

Explode, Shadow, and Colors

To make the pie chart more attractive, you can explode a slice, add shadows, and specify colors:

python
1explode = (0.1, 0, 0, 0)
2plt.pie(sizes, labels=labels, startangle=90, explode=explode, shadow=True, colors=['red', 'green', 'blue', 'yellow'])
3plt.show()

Adding a Legend

You can add a legend to the pie chart using the legend() function:

python
1plt.pie(sizes, labels=labels, startangle=90)
2plt.legend()
3plt.show()

Legend With Header

You can also add a header to the legend:

python
1plt.pie(sizes, labels=labels, startangle=90)
2plt.legend(title="Categories")
3plt.show()

Learning Tips to Remember

  • Think Visually: You must keep in mind that working with Matplotlib is creating art using data. You could think about it as if you had a blast creating colors, shapes, and lines to communicate something interesting.
  • Have Fun Experimenting: Add the following elements, in any way you want-colors, markers, and labels-to your graph and explore how they change its appearance.
  • Practice Makes Perfect: The only way to get good at making creative, clear graphs in Matplotlib is by playing with it more.

FAQs

What can Matplotlib be used for?

What is Matplotlib?

What is the meaning of matplotlib use?

Why Use Matplotlib?

Sign-in First to Add Comment

Leave a comment 💬

All Comments

No comments yet.