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 lines
|
6/ 500 tokens
1
pip install matplotlib
Code Tools

Import Matplotlib

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

python
1 lines
|
8/ 500 tokens
1
import matplotlib.pyplot as plt
Code Tools

Checking Matplotlib Version

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

python
2 lines
|
12/ 500 tokens
1
2
import matplotlib
print(matplotlib.__version__)
Code Tools

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
7 lines
|
24/ 500 tokens
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()
Code Tools

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
2 lines
|
8/ 500 tokens
1
2
plt.plot(x, y, 'o')
plt.show()
Code Tools

Multiple Points

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

python
9 lines
|
31/ 500 tokens
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()
Code Tools

Default X-Points

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

python
3 lines
|
10/ 500 tokens
1
2
3
y = [1, 4, 9, 16]
plt.plot(y)
plt.show()
Code Tools

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
2 lines
|
10/ 500 tokens
1
2
plt.plot(x, y, marker='^')
plt.show()
Code Tools

Format Strings (fmt)

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

python
2 lines
|
12/ 500 tokens
1
2
plt.plot(x, y, 'ro')  # Red circles
plt.show()
Code Tools

Line Reference

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

python
2 lines
|
14/ 500 tokens
1
2
plt.plot(x, y, linestyle='--')  # Dashed line
plt.show()
Code Tools

Color Reference

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

python
2 lines
|
10/ 500 tokens
1
2
plt.plot(x, y, color='green')
plt.show()
Code Tools

Marker Size

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

python
2 lines
|
13/ 500 tokens
1
2
plt.plot(x, y, marker='o', markersize=10)
plt.show()
Code Tools

Marker Color

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

python
2 lines
|
19/ 500 tokens
1
2
plt.plot(x, y, marker='o', markersize=10, markerfacecolor='blue')
plt.show()
Code Tools

Matplotlib Line

Linestyle

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

python
2 lines
|
10/ 500 tokens
1
2
plt.plot(x, y, linestyle=':')
plt.show()
Code Tools

Shorter Syntax

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

python
2 lines
|
18/ 500 tokens
1
2
plt.plot(x, y, 'g^--')  # Green triangles with dashed line
plt.show()
Code Tools

Line Styles

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

python
2 lines
|
11/ 500 tokens
1
2
plt.plot(x, y, linestyle='-.')
plt.show()
Code Tools

Line Color

You can easily customize the line color:

python
2 lines
|
11/ 500 tokens
1
2
plt.plot(x, y, color='purple')
plt.show()
Code Tools

Multiple Lines

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

python
4 lines
|
23/ 500 tokens
1
2
3
4
plt.plot(x1, y1, label="Line 1")
plt.plot(x2, y2, label="Line 2")
plt.legend()
plt.show()
Code Tools

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
4 lines
|
17/ 500 tokens
1
2
3
4
plt.plot(x, y)
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()
Code Tools

Create a Title for a Plot

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

python
3 lines
|
13/ 500 tokens
1
2
3
plt.plot(x, y)
plt.title("Sample Plot")
plt.show()
Code Tools

Set Font Properties for Title and Labels

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

python
5 lines
|
49/ 500 tokens
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()
Code Tools

Matplotlib Adding Grid Lines

Add Grid Lines to a Plot

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

python
3 lines
|
10/ 500 tokens
1
2
3
plt.plot(x, y)
plt.grid(True)
plt.show()
Code Tools

Specify Which Grid Lines to Display

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

python
3 lines
|
17/ 500 tokens
1
2
3
plt.plot(x, y)
plt.grid(axis='y')  # Only grid on y-axis
plt.show()
Code Tools

Set Line Properties for the Grid

You can customize the appearance of the grid lines:

python
3 lines
|
20/ 500 tokens
1
2
3
plt.plot(x, y)
plt.grid(color='gray', linestyle='--', linewidth=0.5)
plt.show()
Code Tools

Matplotlib Subplot

Display Multiple Plots

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

python
7 lines
|
38/ 500 tokens
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()
Code Tools

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
10 lines
|
41/ 500 tokens
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()
Code Tools

Matplotlib Scatter

Creating Scatter Plots

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

python
2 lines
|
7/ 500 tokens
1
2
plt.scatter(x, y)
plt.show()
Code Tools

Compare Plots

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

python
4 lines
|
26/ 500 tokens
1
2
3
4
plt.plot(x, y, label="Line")
plt.scatter(x, y2, color='red', label="Scatter")
plt.legend()
plt.show()
Code Tools

Colors

You can specify colors for scatter plot points:

python
2 lines
|
11/ 500 tokens
1
2
plt.scatter(x, y, color='green')
plt.show()
Code Tools

Color Each Dot

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

python
3 lines
|
21/ 500 tokens
1
2
3
colors = ['red', 'blue', 'green', 'orange']
plt.scatter(x, y, c=colors)
plt.show()
Code Tools

ColorMap

You can apply a colormap to your scatter plot:

python
9 lines
|
41/ 500 tokens
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()
Code Tools

Size

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

python
3 lines
|
16/ 500 tokens
1
2
3
sizes = [20, 50, 100, 200]
plt.scatter(x, y, s=sizes)
plt.show()
Code Tools

Alpha

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

python
2 lines
|
10/ 500 tokens
1
2
plt.scatter(x, y, alpha=0.5)
plt.show()
Code Tools

Combine Color, Size, and Alpha

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

python
6 lines
|
35/ 500 tokens
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()
Code Tools

Matplotlib Bars

Creating Bars

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

python
5 lines
|
17/ 500 tokens
1
2
3
4
5
x = ['A', 'B', 'C', 'D']
y = [3, 8, 1, 10]

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

Bar Color

You can change the color of the bars:

python
2 lines
|
10/ 500 tokens
1
2
plt.bar(x, y, color='orange')
plt.show()
Code Tools

Color Names and Hex Codes

You can use color names or hexadecimal color codes:

python
2 lines
|
14/ 500 tokens
1
2
plt.bar(x, y, color='#4CAF50')  # Hex color
plt.show()
Code Tools

Bar Width and Height

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

python
2 lines
|
9/ 500 tokens
1
2
plt.bar(x, y, width=0.4)
plt.show()
Code Tools

Matplotlib Histograms

Creating Histograms

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

python
4 lines
|
18/ 500 tokens
1
2
3
4
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

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

Matplotlib Pie Charts

Creating Pie Charts

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

python
5 lines
|
24/ 500 tokens
1
2
3
4
5
labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]

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

Labels and Start Angle

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

python
2 lines
|
14/ 500 tokens
1
2
plt.pie(sizes, labels=labels, startangle=90)
plt.show()
Code Tools

Explode, Shadow, and Colors

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

python
3 lines
|
39/ 500 tokens
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()
Code Tools

Adding a Legend

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

python
3 lines
|
17/ 500 tokens
1
2
3
plt.pie(sizes, labels=labels, startangle=90)
plt.legend()
plt.show()
Code Tools

Legend With Header

You can also add a header to the legend:

python
3 lines
|
22/ 500 tokens
1
2
3
plt.pie(sizes, labels=labels, startangle=90)
plt.legend(title="Categories")
plt.show()
Code Tools

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

Matplotlib is a Python-based environment; the package is used to create static, interactive, and animated visualizations. It offers a comprehensive set of tools to create plots like line graphs, bar charts, scatter plots, and histograms to represent the data in the form most suitable for analysis.

Matplotlib is an extensive Python library that provides clear and concise construction of visual representation formats to represent trends, distributions, and relationships in data.

Consequently, using Matplotlib plots would avail easy ways of visualizing the trends, comparing categories, and informing data insights from whatever data set.

You should use Matplotlib because it simplifies the creation of plots, supports a wide range of plots, and will work well with other libraries in Python, especially those such as NumPy and Pandas, for data analysis tasks.

Still have questions?Contact our support team

Related Articles

Sign-in First to Add Comment

Leave a comment 💬

All Comments

No comments yet.