Python Matplotlib

Narayanan
8 min readAug 24, 2023

--

Matplotlib is a popular Python tool used to create static, interactive, and animated visualizations in a variety of forms.

Matplotlib’s ability to generate useful, personalized, and high-quality visuals has made it a must-have tool for data analysts, scientists, engineers, researchers, and educators.

Matpltlib is most typically used in the following domains:

Business and Finance, Data Analysis and Visualization, Data Science and Machine Learning, Engineering and Science, and Geospatial Data.

Let explore on basic things

Importing Matplotlib

Python’s import statement instructs it to load the Matplotlib library. The matplotlib.pyplot submodule contains the most often used Matplotlib processes.

import matplotlib.pyplot as plt

It is mandatory if we process data with Numpy and Pandas; we also need to import those modules; otherwise, they are not needed.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

Creating and displaying plot

To create and display a simple plot in Matplotlib, some essential data is required (x-axis and y-axis).

import matplotlib.pyplot as plt

# x-axis and y-axis data
x = [5, 10, 15, 20, 25]
y = [3, 9, 27, 18, 15]

# Plot based output
plt.plot(x, y)


# Display output
plt.show()

On the above graph, you can see the plot graph is displayed as per the available value, but it is not readable whats on the x-axis, y-axis, and title of the graph. We can set a value for that also.

Label and Title

xlabel() — Set label for x-axis.

ylabel() — Set label for y-axis.

title() — Set title for graph or plot.

import matplotlib.pyplot as plt

# x-axis and y-axis data
x = [5, 10, 15, 20, 25]
y = [3, 9, 27, 18, 15]

# Plot based output
plt.plot(x, y)

# labels and title for plot
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Line Plot')

# Display output
plt.show()

Legend

In Matplotlib, a legend is a graphical approach to identify the various lines or bars in a plot. It generally appears in a box.

import matplotlib.pyplot as plt

# x-axis and y-axis data
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 2, 6, 12]
y2 = [3, 12, 15, 6, 9]

# Plot based output
# Denoting label for legend
plt.plot(x, y1, label='A')
plt.plot(x, y2, label='B')

# labels and title for plot
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Line Plot with Legend')

# Add a legend
plt.legend()

# Display output
plt.show()

Annotation

Annotations can be used to add text, arrows, or other forms to a plot. They are used to draw attention to key areas or elements in a plot.

Here we are displaying an arrow annotation. The first element is the word to display on the graph, followed by xy, which denotes the place you need to highlight, then on xytext, you should point where the word should be placed, and finally, arrow props “facecolor” for the color of the arrow, and “shrink” is the distance between the arrow point and the line point.

import matplotlib.pyplot as plt

# x-axis and y-axis data
x = [1, 2, 3, 4, 5]
y = [3, 9, 27, 18, 15]

# Plot based output
# Denoting label for annotation
plt.plot(x, y, label='Data')

# labels and title for plot
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('Line Plot with Annotation')

# Adding arrow annotations
plt.annotate('High', xy=(3, 27), xytext=(3, 9),
arrowprops=dict(facecolor='green', shrink=0.10),
)

# Display output
plt.show()

Linestyle

The linestyle specifies the appearance of a line plot. It is used to modify the line’s appearance, such as its thickness, color, and dashes.

import matplotlib.pyplot as plt

# x-axis and y-axis data
x = [1, 2, 3, 4, 5]
y1 = [1, 1, 1, 1, 1]
y2 = [2, 2, 2, 2, 2]
y3 = [3, 3, 3, 3, 3]
y4 = [4, 4, 4, 4, 4]
y5 = [5, 5, 5, 5, 5]

# Plot based output
plt.plot(x, y, label='Data')
plt.plot(x, y1,color='black',label='Line 1')
plt.plot(x, y2, color='blue', linestyle='--', label='Line 2')
plt.plot(x, y3, color='red', ls=':', label='Line 3')
plt.plot(x, y4, color='pink',linestyle='', label='Line 4')
plt.plot(x, y5, color='green', linestyle='-.', label='Line 5')

# labels and title for plot
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Customized Line Plot')
plt.legend()

# Display output
plt.show()

Line 1 — , Line 2 — — , Line 3 …., Line 4 ‘ ’ or empty, Line 5 _._.

Adding Legend position and style

In Matplotlib, we can change the default position and font size of the legend.

#same as before
plt.legend(loc='upper right', fontsize=12)

Adding Marker

In Matplotlib, we can set markers to show all the points in a bullet.

import matplotlib.pyplot as plt

# x-axis and y-axis data
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 2, 6, 12]
y2 = [3, 12, 15, 6, 9]

# Plot with marker
plt.plot(x, y1, label='A')
plt.plot(x, y2, label='B', color='red', marker='o')

# labels and title for plot
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot with Marker')

# Add a legend
plt.legend()

# Display output
plt.show()

Setting Axes

In Matplotlib, by setting values on the xlim and ylim functions, the graph will focus only on these points (it does not show a full graph).

import matplotlib.pyplot as plt

# x-axis and y-axis data
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 2, 6, 12]
y2 = [3, 12, 15, 6, 9]

# Plot with marker
plt.plot(x, y1, label='A')
plt.plot(x, y2, label='B', color='red', marker='o')

# labels and title for plot
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot with xlim and ylim')

# Add a legend
plt.legend()

# Setting xlim and ylim
plt.xlim(3, 6)
plt.ylim(4, 10)

# Display output
plt.show()

Setting Grid Background

The grid in Matplotlib is a collection of lines drawn behind the data points in a plot. You can change the linestyle to ‘solid’, ‘dashed’, ‘dotted’, ‘dashdot’, and ‘ ’. Then set alpha for the transparency value (0.1–1), and you can also set line width.

import matplotlib.pyplot as plt

# x-axis and y-axis data
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 2, 6, 12]
y2 = [3, 12, 15, 6, 9]

# Plot with marker
plt.plot(x, y1, label='A')
plt.plot(x, y2, label='B', color='red', marker='o')

# labels and title for plot
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot with Grid lines')

# Add a legend
plt.legend()

# Setting grid
plt.grid(True, linestyle='solid', alpha=1)
#plt.grid(True, linestyle='dashed', alpha=1, linewidth=1)

# Display output
plt.show()

Setting Background color

The set_facecolor() function in Matplotlib can be used to change the background color.

import matplotlib.pyplot as plt

# x-axis and y-axis data
x = [1, 2, 3, 4, 5]
y1 = [2, 4, 2, 6, 12]
y2 = [3, 12, 15, 6, 9]

# Plot with marker
plt.plot(x, y1, label='A',color='green')
plt.plot(x, y2, label='B', color='red', marker='o')

# labels and title for plot
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot with Background color')

# Add a legend
plt.legend()

# Setting Background color
plt.gca().set_facecolor('#989898')

# Display output
plt.show()

Figure Size and DPI

To alter the dimensions and quality of your plots, you can use figure size and DPI (dots per inch).

import matplotlib.pyplot as plt

# Create data
x = [5, 10, 15, 20, 25]
y = [3, 9, 27, 18, 15]


# Create a basic plot
plt.plot(x, y)
# Add labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot with default size and dpi')

# Figure size finder
fig = plt.gcf()
size = fig.get_size_inches()*fig.dpi
print("Figure size and dpi - ",size,fig.dpi)

# Adjust the figure size
plt.figure(figsize=(10, 10),dpi=180)

# Display the plot
plt.show()

Subplot

Subplots are used to create numerous plots within a single figure. This lets you to structure and compare multiple datasets, visualizations, or features of your data.

import matplotlib.pyplot as plt

# x-axis and y-axis data
x = [1, 2, 3, 4, 5]
y1 = [3, 9, 27, 18, 15]
y2 = [2, 5, 8, 6, 12]
y3 = [8, 3, 5, 2, 9]
y4= [5,1,6,8,2]

#Setting 2*2 graphs
fig,ploting = plt.subplots(nrows=2, ncols=2, figsize=(10, 6))

# Plot based row and column based
ploting[0,0].plot(x, y1,color='black',label='Line 1')
ploting[0,0].set_title('Plot-1')
ploting[0,1].plot(x, y2, color='blue', linestyle='--', label='Line 2')
ploting[0,1].set_title('Plot-2')
ploting[1,0].plot(x, y3, color='red', label='Line 3')
ploting[1,0].set_title('Plot-3')
ploting[1,1].plot(x, y4, color='green', label='Line 3')
ploting[1,1].set_title('Plot-4')

#Space between plots
plt.tight_layout()

# Display output
plt.show()

Save figure

The savefig() function in Matplotlib allows you to save your plots as picture files. This allows you to save your visualizations for use in presentations and reports.

import matplotlib.pyplot as plt

# Create data
x = [5, 10, 15, 20, 25]
y = [3, 9, 27, 18, 15]

# Create a basic plot
plt.plot(x, y)
# Add labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Line Plot')

# # Save the plot PNG image
# plt.savefig('plot_op.png')

# # Other formats
# plt.savefig('plot_op.jpg')
# plt.savefig('plot_op.svg')
# plt.savefig('plot_op.pdf')

# Higher resolution
# For png
plt.savefig('plot_op.png',dpi=200)

# Display plot
# savefig should called before show()
plt.show()

Matplotlib is used for constructing various types of plots, such as line plots, scatter plots, bar plots, histograms, pie charts, and more.
Matplotlib is widely used in the Python community and interfaces with data science libraries such as NumPy, Pandas, and SciPy.

So far, the basics of Matplotlib are covered. I hope you like it.

--

--

Narayanan

Front-end Development | Back-end development | Data Science | Data Visualization | Hodophile | Booklover