Matplotlib in Python

Published:5 min read

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.

Matplotlib library


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
1
pip install matplotlib

Import Matplotlib

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

python
1
import 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
1
2
import matplotlib
print(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
1
2
3
4
5
6
7
import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [1, 4, 9, 16]

plt.plot(x, y)
plt.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
1
2
plt.plot(x, y, 'o')
plt.show()

Multiple Points

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

python
1
2
3
4
5
6
7
8
9
x1 = [1, 2, 3, 4]
y1 = [1, 4, 9, 16]

x2 = [1, 2, 3, 4]
y2 = [2, 4, 6, 8]

plt.plot(x1, y1, 'o')
plt.plot(x2, y2)
plt.show()

Default X-Points

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

python
1
2
3
y = [1, 4, 9, 16]
plt.plot(y)
plt.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
1
2
plt.plot(x, y, marker='^')
plt.show()

Format Strings (fmt)

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

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

Line Reference

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

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

Color Reference

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

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

Marker Size

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

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

Marker Color

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

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

Matplotlib Line

Linestyle

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

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

Shorter Syntax

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

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

Line Styles

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

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

Line Color

You can easily customize the line color:

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

Multiple Lines

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

python
1
2
3
4
plt.plot(x1, y1, label="Line 1")
plt.plot(x2, y2, label="Line 2")
plt.legend()
plt.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
1
2
3
4
plt.plot(x, y)
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()

Create a Title for a Plot

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

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

Set Font Properties for Title and Labels

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

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

Matplotlib Adding Grid Lines

Add Grid Lines to a Plot

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

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

Specify Which Grid Lines to Display

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

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

Set Line Properties for the Grid

You can customize the appearance of the grid lines:

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

Matplotlib Subplot

Display Multiple Plots

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

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

plt.subplot(1, 2, 2)  # 1 row, 2 columns, position 2
plt.plot(x, y2)

plt.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
1
2
3
4
5
6
7
8
9
10
plt.subplot(1, 2, 1)
plt.plot(x, y)
plt.title("First Plot")

plt.subplot(1, 2, 2)
plt.plot(x, y2)
plt.title("Second Plot")

plt.suptitle("Main Title")
plt.show()

Matplotlib Scatter

Creating Scatter Plots

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

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

Compare Plots

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

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

Colors

You can specify colors for scatter plot points:

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

Color Each Dot

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

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

ColorMap

You can apply a colormap to your scatter plot:

python
1
2
3
4
5
6
7
8
9
import numpy as np

x = np.random.rand(50)
y = np.random.rand(50)
colors = np.random.rand(50)

plt.scatter(x, y, c=colors, cmap='viridis')
plt.colorbar()
plt.show()

Size

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

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

Alpha

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

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

Combine Color, Size, and Alpha

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

python
1
2
3
4
5
6
sizes = 1000 * np.random.rand(50)
alpha = 0.5

plt.scatter(x, y, c=colors, s=sizes, alpha=alpha, cmap='plasma')
plt.colorbar()
plt.show()

Matplotlib Bars

Creating Bars

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

python
1
2
3
4
5
x = ['A', 'B', 'C', 'D']
y = [3, 8, 1, 10]

plt.bar(x, y)
plt.show()

Bar Color

You can change the color of the bars:

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

Color Names and Hex Codes

You can use color names or hexadecimal color codes:

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

Bar Width and Height

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

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

Matplotlib Histograms

Creating Histograms

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

python
1
2
3
4
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

plt.hist(data, bins=4)
plt.show()

Matplotlib Pie Charts

Creating Pie Charts

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

python
1
2
3
4
5
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]

plt.pie(sizes, labels=labels)
plt.show()

Labels and Start Angle

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

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

Explode, Shadow, and Colors

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

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

Adding a Legend

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

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

Legend With Header

You can also add a header to the legend:

python
1
2
3
plt.pie(sizes, labels=labels, startangle=90)
plt.legend(title="Categories")
plt.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.

Frequently Asked Questions

Related Articles

Sign-in First to Add Comment

Leave a comment 💬

All Comments

No comments yet.