Creating and Configuring a Line Chart (line Plot) in Matplotlib Using Python for Beginners

by xanthium-enterprises in Circuits > Electronics

212 Views, 2 Favorites, 0 Comments

Creating and Configuring a Line Chart (line Plot) in Matplotlib Using Python for Beginners

creating-simple-line-chart.jpg

In this Instructable, You will learn to create and customize a line chart (plot) for displaying varying data like sensor readings, temperature, g-forces etc using the popular Matplotlib Library and Python.

This instructable is intended for a user who is new to the Matplotlib library and want to plot the data gathered by a datalogger or a data acquisition system.



We will explain the main concepts behind the Matplotlib Library and then slowly guide the user on to creating and customizing multiple types of line plots using Python and Matplotlib.

Line charts are widely used to represent changes in data over a continuous or ordered range. They help reveal trends, patterns, fluctuations, and sudden variations that may not be obvious from raw numbers alone. This makes them particularly useful for analyzing time-series data, sensor measurements, temperature, speed, and other continuously changing values.

You can find all the source codes used here along with the original article using the below link.

  1. check out our Comprehensive MatplotLib Library Charting Tutorial for Absolute Beginners here


Supplies

Mpl_screenshot_figures_and_code.png
240px-Python-logo-notext.svg.png.png

All the supplies used in the Instructable can be downloaded from the internet for free or from our website.

  1. Basic PC (Linux/windows) or Mac
  2. Text Editor
  3. Python Interpreter


Source codes for plotting tutorials using Matplotlib


  1. All the source codes for our Matplotlib can be downloaded from our Github Repo
  2. or our Main website

Installing Matplotlib Python Ploting Library

You can install matplotlib charting library on your Python installation using the pip command

python -m pip install matplotlib


On Linux ,You may need to create a virtual environment before doing this.

If you are new virtual environments .Here is a

  1. Tutorial on how to create a VENV virtual environments in Python on Linux OS


You can use an IDE like Thonny and install it from its repo directly too.

Fundamental Concepts Behind Matplotlib Charts (plots)

figure-vs-axes-matplotlib.jpg
figure-with-multiple-axes.jpg
multiple-figure-with-multiple-axes.jpg

The two main concepts that you have to understand before creating a Matplotlib chart or graph are:

  1. Figure
  2. Axes


What is a Figure in MatplotLib

A Figure is the whole main window or canvas that contains our graphs, plots, titles, labels, and other visual elements. Think of the Figure as the container or the overall space in which our chart is created.

A single Figure can contain one or multiple Axes, which allows us to create multiple plots within the same window.


What is an Axes

Axes is the actual plotting area where our graphs or plots are drawn. It is the part of the Figure where we display our data using line charts, bar charts, scatter plots, and other types of visualizations.

An Axes can also contain things such as the x-axis, y-axis, title, labels, grid, legend, and the plotted data.

For example, if we create a Figure containing two different graphs, each graph will generally have its own Axes.


Important Distinction

In Matplotlib, Axes and Axis are different concepts.

  1. Axes → The actual plotting area where the graph is drawn.
  2. Axis → The individual x-axis or y-axis that provides the scale and coordinates for the plot.


1 Figure ,Multiple Axes on Matplotlib

A single Matplotlib Figure can have multiple Axes as shown below. No Values have been plotted to the axes in the below example .

Code for creating Multiple axes on a Single Figure

import matplotlib.pyplot as plt
figure,axes = plt.subplots(nrows=2,ncols=2) # this will create# 4 axes shown below
plt.show()


single Matplotlib Figure can have multiple Axes



Multiple Figures ,Multiple Axes

Matplotlib library supports Multiple Figures and multiple axes as shown below. Multiple Figures will generate multiple windows of Matplotlib as shown below.

Here is the code

import matplotlib.pyplot as plt

figure1,axes1 = plt.subplots(nrows=1,ncols=2) #create Figure1 and its axes
figure2,axes2 = plt.subplots(nrows=2,ncols=3) #create Figure2 and its axes

plt.show()



Fundamental Concepts Behind Matplotlib Charts

Creating Your First Line Chart (plot) With Matplotlib

creating-simple-line-chart (2).jpg

Now we will create a simple Line Chart or line plot using the Matplotlib Python library.

A line plot is one of the most commonly used types of charts and is useful for showing how values change or vary across different points.

To create a line plot in Matplotlib, we need to follow a few basic steps.

First, we create two lists containing the x and y values that we want to visualize. The x values represent the values along the horizontal axis, while the y values represent the corresponding values along the vertical axis. These pairs of values are used by Matplotlib to determine the points that need to be plotted and connected to form the line.

x= [1,2,3,4, 5,6, 7,8, 9,10,11,12,13,14,15] #list of values on x axis
y= [-5,0,5,10,0,20,0,12,7,-1,3,8,2,0,-16] #list of values on y axis


After creating the data, the next step is to create a Figure and Axes object using the subplots() method.

figure,axes = plt.subplots() # creates a drawing area for your graph
# returns a figure and an axes object

The Figure represents the overall canvas or window, while the Axes represents the actual plotting area where our line chart will be drawn.

axes.plot(x,y,'-o') # plot x,y values on axes object.


Once we have the Axes object, we can use its .plot() method to plot the x and y values on the plotting area. Matplotlib will take these values, place the corresponding points on the graph, and connect them with a line.

plt.show()

Finally, after creating the plot, we use the plt.show() method to display the chart on the screen. This allows us to see the final visualization generated by Matplotlib. Therefore, the basic process of creating a line chart can be summarized as: create the x and y data, create the Figure and Axes, plot the data using the .plot() method, and finally display the chart using the .show() method.


Here is the full code for creating a simple line chart in Matplotlib

#Simple Line chart

import matplotlib.pyplot as plt


x= [1,2,3,4, 5,6, 7,8, 9,10,11,12,13,14,15] #list of values on x axis
y= [-5,0,5,10,0,20,0,12,7,-1,3,8,2,0,-16] #list of values on y axis

figure,axes = plt.subplots() # creates a drawing area for your graph
# returns a figure and an axes object
# tuple expansion

axes.plot(x,y,'-o') # plot x,y values on axes object.


#axes.plot(x,y,'r--^') # colour of line=red,dashed line,triangle marker^

axes.set_title('Name of the Axes') #set the name of the Axes
axes.grid(True) #show grid lines

figure.canvas.manager.set_window_title('Name of the Window') # Setting the name of the Window/Figure

plt.show()

A More Complex Line Chart (plot) Using Matplotlib Library

creating-comprehensive-line-chart.jpg

Now that we understand the basic concepts of Figure and Axes,

let us create a more feature rich and comprehensive Line plot using Matplotlib (shown above) . Instead of creating a simple line plot, we will customize the chart to demonstrate some of the important components and features.

For example, we will learn how to add and customize grid lines, work with major and minor ticks, add a legend to identify different lines, and change the colors and appearance of the plotted lines and grid lines.

We will also see how these different elements can be combined to make our chart more readable, informative, and visually appealing

Here is the Python Matplotlib code for creating a more complex plot with markers, plot line, legend ,grid lines etc

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator

x= [1, 2,3,5, 5,6, 7,8, 9,10,11,12,13,14,15]
y= [-5,0,5,10,0,20,0,12,7,-1,5, 8,2,0,-16]

figure,ax = plt.subplots() # creates a drawing area for your graph

#Setting up how the plot should look and feel
ax.plot(x,
y,
linestyle = '--',
linewidth = 1,
marker = 'o',
markersize = 5,
color = 'red', #
label = 'Name plot'

)

#set the name of the Axes object
ax.set_title('Name of the Axes') #set the name of the Axes
ax.set_xlabel("X values")
ax.set_ylabel("Y values")

#Controlling the ticks on x any axis
ax.xaxis.set_major_locator(MultipleLocator(1)) #spacing = 1 units
ax.yaxis.set_major_locator(MultipleLocator(5)) #spacing = 5 units

ax.minorticks_on() #Activate Minor ticks

ax.legend()

#Control how the Grid lines Behave
ax.grid(True)
ax.axhline(0, color="blue", linewidth=1)

figure.canvas.manager.set_window_title('Name of the Window')

plt.show()


Understanding the subplots() Method


The subplots() method is one of the most commonly used functions in Matplotlib for creating a Figure and one or more Axes.

figure,ax = plt.subplots() # creates a drawing area for your graph

plt.subplots() creates a Figure and one or more Axes objects for us.Instead of creating the Figure and Axes separately, Matplotlib provides this convenient method to create them together.

We then use the ax object to plot values on the graph using .plot() method


Understanding the .plots() Method

Once we have created the Figure and Axes objects and prepared our x and y values, the next step is to actually draw the graph.

For this, Matplotlib provides the .plot() method.

#Setting up how the plot should look and feel
ax.plot(x,
y,
linestyle = '--',
linewidth = 1,
marker = 'o',
markersize = 5,
color = 'red', #
label = 'Name plot'

)

The .plot() method is used to plot the provided x and y values on the Axes, which is the actual plotting area of our chart. Matplotlib takes each corresponding pair of x and y values, places them as points on the graph, and then connects those points with a line. This is what creates the line chart.


One of the useful features of the .plot() method is that it provides many parameters that allow us to control the appearance and style of the line. For example, we can change the line style, line width, line color, marker style, marker size, and provide a label for the plotted line

we will explain this in details below.


Setting the Window Title of your Matplotlib Graph

When you display a Matplotlib chart, the chart is usually shown inside a window provided by the graphical backend. By default, the title of this window may be something generic, such as "Figure 1" .

You can change that using

figure.canvas.manager.set_window_title('Name of the Window')


set_window_title() applies to GUI backends that provide an actual window.

If you are running Matplotlib in environments such as Jupyter Notebook, there may be no separate application window, so this method may not have a visible effect.

Customizing Line Styles and Appearances of Line Plot in Matplotlib

image_258.png

When creating a line graph using the plot() function, several parameters can be used to control how the line looks.

The most commonly used parameters are

  1. color -> determines the color of the line
  2. linestyle -> determines the pattern of the line ,Eg solid line ("-"), dashed line ("--") etc
  3. linewidth -> controls the thickness of the line
  4. marker -> specifies the shape of the marker
  5. markersize -> size of these markers
  6. alpha -> controls the transparency of the line


Here is the code that illustrate the various parameters used in the .plot() method

ax.plot(x,
y,
linestyle = '--', #'--' dashed line , '-' Straight line ,
linewidth = 1,
marker = 'o', #'o' o marker ,'s' square marker
markersize = 5,
color = 'red', #other colours ,blue,green,
label = 'Name of the plot' # used by the Legend

)


Here we will learn how to change the color and thickness of the plot line.


Changing the line color in Matplotlib


You can just give the required color name using .

color = 'red', #other colors ,blue, green,

or you can use specific hex value

color = '#FF4733'


Changing the line width in Matplotlib


You can change the thickness of the plot line using

linewidth = 1, #1 point wide line

where the values are in points (pts) not pixels.


Changing the line style in Matplotlib

The line style determines the pattern or appearance of a line in a plot.

You can change the line style using the linestyle parameter.

Matplotlib provides several built-in line styles.

  1. solid line is represented by "-",
  2. dashed line by "--",
  3. dotted line by ":",
  4. a dash-dot line by "-.".

Changing line styles is especially useful when a graph contains multiple lines because different patterns make it easier to distinguish between datasets, even when they have similar colors

ax.plot(x,
y,
linestyle = '--', #'--' dashed line , '-' Straight line ,':' dot line ,'-.' dash-dot line
linewidth = 1,
color = 'red', #other colours ,blue,green,red etc also hex values color='#FF5733'

)


Here is an example of multiple line styles in matplotlib.


Customizing Line Styles and  Appearances in Matplotlib

Customizing Marker Shapes and Sizes for Line Plot in Matplotlib

image_259.png

In Matplotlib, a marker is a symbol used to represent each individual data point on a plot.

When we create a line graph, Matplotlib connects the data points with a line, and markers can be added to make the individual points more visible.

For example, if our x and y values are plotted on a graph, you may see small circles at the locations where the corresponding x and y values meet. These circles are called markers.

Markers are particularly useful when we want to clearly identify individual observations or data points in a graph

By default, a line plot may not display markers, but we can add them by using the marker parameter in the .plot() method.

Changing Marker shapes

Matplotlib provides many different marker shapes, allowing us to choose a symbol that best represents our data.

For example,

  1. "o" creates a circular marker,
  2. "s" creates a square marker,
  3. "^" creates a triangle pointing upward, "
  4. "*" creates a star,
  5. "+" creates a plus sign,
  6. "x" creates an X-shaped marker.


The marker shape can therefore be changed simply by assigning a different value to the marker parameter.

ax.plot(x,
y,
...
marker = 's', #'s' square marker ,

)



Changing Marker Size

The size of the marker can be controlled using the markersize parameter.. A larger value produces larger markers, while a smaller value produces smaller markers

ax.plot(x,
y,
...
marker = 's', #'s' square marker ,
markersize = 5,

)

Here is an example .

Controlling Marker shape and size in Matplotlib

In addition to controlling the shape and size, . We can change the color inside the marker using markerfacecolor, change the border color using markeredgecolor, and control the thickness of the border using markeredgewidth. These options are useful when we want the data points to stand out clearly from the line.


Adding Legends to Matplotlib Plots

image_260.png

A legend in Matplotlib is a small box displayed on a graph that explains what each line, marker, or dataset represents.

Legends are especially useful when a plot contains multiple lines or data series, because they help the viewer identify which line corresponds to which dataset.

For example, if a graph contains separate lines for sales in 2024 and 2025, a legend can indicate which line represents each year.

In Matplotlib, a legend is created by giving each plotted line a label using the label parameter and then calling the plt.legend() function.

axes.plot(x,
y,
.....
label = 'Name of the plot' #used by the Legend
....
)
axes.legend()



Labeling the X and Y Axes of Line Plot in Matplotlib

image_261.png
Screenshot 2026-08-29 134833.png

Axes vs Axis

Here, we are going to give a name to our plot, or more precisely, to our Axes object. It is important to understand the difference between an Axes and an Axis in Matplotlib, because these two terms sound similar but refer to different things.


In Matplotlib, the Axes object represents the entire plotting area where the data is displayed. It includes the coordinate system, the X and Y axes, the plotted lines or markers, labels, title, legend, grid, and other elements associated with that particular plot. In simple terms, you can think of the Axes object as the complete graph or plotting area.

fig, ax = plt.subplots()

here ax is the Axes Object.


An Axis, on the other hand, refers specifically to one of the coordinate axes within the Axes object. A typical two-dimensional plot has two Axis objects: the X-axis, which usually represents the horizontal direction, and the Y-axis, which represents the vertical direction. Therefore, an Axes object contains the X and Y Axis objects.

Figure is the overall canvas, the Axes is the actual plotting area within the Figure, and the Axis objects are the X and Y coordinate axes contained within the Axes


Labeling the Axes Object in Matplotlib


You can label the Axes object or give a name to your plot using

axes.set_title('Name of the Axes') #set the name of the Axes

This will display the text "Name of the Axes" at the top of the plotting area, as shown in the figure below


Labeling the X and Y Axes in Matplotlib


Labeling the X and Y Axis of Matplotlib plot


we can add descriptive labels to the X-axis and Y-axis of a plot to clearly explain what each axis represents.Axis labels make the graph easier to understand and provide context for the data being displayed.


We can label the X-axis using the set_xlabel() method and the Y-axis using the set_ylabel() method of the Axes object.

axes.set_xlabel("X values") # set the name of the x axis
axes.set_ylabel("Y values") # set the name of the y axis


You can also change the color, fontsize as shown below.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

x = [1, 2, 3, 4, 5]
y = [10, 20, 1, 40, 60]

ax.plot(x, y)
ax.set_title('Name of the Axes object ')

ax.set_xlabel("Time", color = 'green',fontsize=12, fontweight="bold")
ax.set_ylabel("Temperature", color = 'red', fontsize=12, fontweight="bold")

plt.show()

If you run this it would look like

Labeling the X and Y Axes in Matplotlib

Adding Gridlines to Matplotlib Line Plots for Legibility

image_263.png
image_262.png

Gridlines are horizontal and vertical lines displayed across the plotting area to make it easier to read and compare values on a graph.

They provide visual reference points that help us determine the approximate value of a data point by following the gridline to the corresponding X-axis or Y-axis value.


You can activate the Gridlines on Matplotlib plot using

ax.grid(True) #activate the Gridlines on Matplotlib

ax.grid() adds both horizontal and vertical gridlines to the plotting area. This makes it easier to identify the position and value of each data point.

We can also control the appearance of the gridlines by specifying parameters such as linestyle, linewidth, color, and alpha

You can change the color of the gridlines using

ax.grid(color='green') # gridlines will be green


Labeling the X and Y Axes in Matplotlib



ax.grid(
axis = 'both', # x and y axis gets grid lines
visible = True, # Grid visibility
color = 'blue', # Grid Colour
linestyle = ':', # Grid line style '--', #'--' dashed line , '-' Straight line ,':' Straight line ,'-.' dash-dot line
linewidth = 1, # thickness of the Grid line
alpha = 0.5 # transparency of the gridline ,0 fully transparent,1 fully opaque
)


What Are Ticks? Understanding and Customizing Ticks in Matplotlib Plots

image_266.png
image_267.png
image_268.png
image_269.png
image_270.png

Matplotlib Ticks are the small marks that appear along the X-axis and Y-axis of a plot. They indicate specific positions or values on an axis and help us understand the scale of the graph.

For example, if the X-axis represents time and displays values such as 0, 10, 20, 30, 40, each of these values is associated with a tick.

The small marks along the axis are called tick marks, while the numbers or text displayed next to them are called tick labels.


What Are Ticks Understanding and Customizing Ticks in Matplotlib



Ticks are automatically generated by Matplotlib based on the range and type of data being plotted. However, the default ticks are not always ideal for a particular visualization. We may want to change their position, frequency, labels, font size, color, or rotation to make the graph easier to read.


Manually Placing Ticks on the Axis


You can use the

  1. set_xticks() method to manually place ticks on the X-axis
  2. and the set_yticks() method to manually place ticks on the Y-axis.


We simply provide a list of values representing the positions where we want the ticks to appear.

#manually place ticks on the x and y axis using set_xticks() for the x-axis and set_yticks()
axes.set_xticks([0, 2, 5, 10])
axes.set_yticks([0, 2, 5, 10])

This will result in

What Are Ticks Understanding and Customizing Ticks in Matplotlib


Automatically Placing Ticks at a Specific Interval

sometimes we want Matplotlib to continue placing the ticks automatically while also specifying a particular interval between them.

For example, instead of manually providing [0, 2, 5, 10], we may want the X-axis to automatically display a tick every 5 units.

This can be achieved using tick locators from matplotlib.ticker.

The MultipleLocator class is used for this purpose. It allows us to specify the interval between consecutive ticks. For example.

from matplotlib.ticker import MultipleLocator #import the MultipleLocator

axes.xaxis.set_major_locator(MultipleLocator(5)) # place major ticks at multiples of 5 on X Axis

axes.yaxis.set_major_locator(MultipleLocator(5))# place major ticks at multiples of 5 on Y Axis

Here there will be an interval of 5 between Ticks as shown below.


What Are Ticks Understanding and Customizing Ticks in Matplotlib


What are Major and Minor Ticks

In Matplotlib, major ticks and minor ticks are two types of tick marks that can be displayed along the X-axis and Y-axis.

  1. Major ticks are the primary tick marks on an axis and are usually placed at larger, more meaningful intervals. They normally have tick labels displayed next to them.
  2. Minor ticks, on the other hand, are smaller subdivisions placed between the major ticks. They are generally used to provide additional reference points and, by default, do not usually have labels


You can activate the Minor Ticks using

ax.minorticks_on() #Activate Minor ticks




What Are Ticks Understanding and Customizing Ticks in Matplotlib



You can change the Minor Tick interval using.

axes.xaxis.set_minor_locator(MultipleLocator(1))
axes.yaxis.set_minor_locator(MultipleLocator(0.5))

this will result in



What Are Ticks Understanding and Customizing Ticks in Matplotlib

Creating Multiple Subplots Inside a Single Figure in Matplotlib

image_271.png
image_272.png

Here we will learn to create multiple plots or charts inside the same Matplotlib Window (figure) using Python

A subplot is an individual plotting area placed inside a larger Figure. Instead of creating several separate figures for different graphs, we can place multiple plots together within a single figure.

This is especially useful when we want to compare different datasets, display related visualizations side by side, or analyze several aspects of the same data.

A Figure can contain one or more Axes objects, where each Axes object represents an individual plotting area. For example, if we create four subplots, the Figure will contain four separate Axes objects.

The easiest way to create multiple subplots is by using the plt.subplots() function.

Here we will create two or more plots in the same window using matplotlib as shown in the below figure.

Creating multiple Plots on the Same Window

The code for creating the two graphs in the same window using Matplotlib is shown below.

#creating two plots on the same window
import matplotlib.pyplot as plt

#data for the first plot
x1= [1, 2,3,4, 5,6, 7,8, 9,10,11,12,13,14,15] #list of values on x axis
y1= [1,0,5,10,11,20,22,32,37,44,43,48,52,60,66] #list of values on y axis

#data for second plot
x2= [1, 2,3,4, 5,6, 7,8, 9,10,11,12,13,14,15] #list of values on x axis
y2= [100,90,85,70,61,50,42,32,37,44,43,48,52,60,66] #list of values on y axis

figure,axes = plt.subplots(nrows=1,ncols=2,figsize=(12,5)) # create two axes,side by side
# single row ,double columns
# figsize specifies the size of the Matplotlib figure.
# figsize=(width,height) in inches
axes[0].plot(x1,y1) # plot the first graph
axes[1].plot(x2,y2) # plot the second graph

axes[0].set_title('Plot1')
axes[1].set_title('Plot2')

axes[0].grid(True) # enable grid for first graph
axes[1].grid(True) # enable grid for second graph

plt.tight_layout() #automatically adjusts the spacing between subplots so that titles, axis labels, and tick labels don't overlap

figure.canvas.manager.set_window_title('Two Plots in One Figure') # Setting the name of the Window/Figure

plt.show()


The basic idea of creating two plots(graphs) inside a single window is to create two axes object using the subplots() method.

Here we are using the nrows and ncols parameter in the subplots() method to define the number and position of the graphs (axes object).

Here we will have a single row (nrows=1) and two column of graphs (ncols=2).This will create two axes objects which we will use for plotting our data.

That means that the graph will be placed side by side.

Creating multiple Plots on the Same Window

Now you can access each axes object using array notation and call its corresponding plot() function.

axes[0].plot(x1,y1) # plot the first graph
axes[1].plot(x2,y2) # plot the second graph

axes[0].set_title('Plot1')
axes[1].set_title('Plot2')

axes[0].grid(True) # enable grid for first graph
axes[1].grid(True) # enable grid for second graph