The Wayback Machine - https://web.archive.org/web/20240910173102/https://www.geeksforgeeks.org/line-chart-in-matplotlib-python/
Open In App

Line chart in Matplotlib – Python

Last Updated : 13 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Matplotlib is a data visualization library in Python. The pyplot, a sublibrary of Matplotlib, is a collection of functions that helps in creating a variety of charts. Line charts are used to represent the relation between two data X and Y on a different axis. In this article, we will learn about line charts and matplotlib simple line plots in Python.

Python Line chart in Matplotlib

Here, we will see some of the examples of a line chart in Python using Matplotlib:

Matplotlib Simple Line Plot

In this example, a simple line chart is generated using NumPy to define data values. The x-values are evenly spaced points, and the y-values are calculated as twice the corresponding x-values.

Python
# importing the required libraries
import matplotlib.pyplot as plt
import numpy as np

# define data values
x = np.array([1, 2, 3, 4])  # X-axis points
y = x*2  # Y-axis points

plt.plot(x, y)  # Plot the chart
plt.show()  # display

Output:

Image

Simple line plot between X and Y data

We can see in the above output image that there is no label on the x-axis and y-axis. Since labeling is necessary for understanding the chart dimensions. In the following example, we will see how to add labels, Ident in the charts.

Python
import matplotlib.pyplot as plt
import numpy as np


# Define X and Y variable data
x = np.array([1, 2, 3, 4])
y = x*2

plt.plot(x, y)
plt.xlabel("X-axis")  # add X-axis label
plt.ylabel("Y-axis")  # add Y-axis label
plt.title("Any suitable title")  # add title
plt.show()

Output:     

Image

Simple line plot with labels and title

Line Chart with Annotations

In this example, a line chart is created using sample data points. Annotations displaying the x and y coordinates are added to each data point on the line chart for enhanced clarity.

Python
import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Create a line chart
plt.figure(figsize=(8, 6))
plt.plot(x, y, marker='o', linestyle='-')

# Add annotations
for i, (xi, yi) in enumerate(zip(x, y)):
    plt.annotate(f'({xi}, {yi})', (xi, yi), textcoords="offset points", xytext=(0, 10), ha='center')

# Add title and labels
plt.title('Line Chart with Annotations')
plt.xlabel('X-axis Label')
plt.ylabel('Y-axis Label')

# Display grid
plt.grid(True)

# Show the plot
plt.show()

Output:

Screenshot-2024-01-03-130417

Multiple Line Charts Using Matplotlib 

We can display more than one chart in the same container by using pyplot.figure() function. This will help us in comparing the different charts and also control the look and feel of charts.

Python
import matplotlib.pyplot as plt
import numpy as np


x = np.array([1, 2, 3, 4])
y = x*2

plt.plot(x, y)
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Any suitable title")
plt.show()  # show first chart

# The figure() function helps in creating a
# new figure that can hold a new chart in it.
plt.figure()
x1 = [2, 4, 6, 8]
y1 = [3, 5, 7, 9]
plt.plot(x1, y1, '-.')

# Show another chart with '-' dotted line
plt.show()

Output:

ImageImage

Multiple Plots on the Same Axis

Here, we will see how to add 2 plots within the same axis.

Python
import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4])
y = x*2

# first plot with X and Y data
plt.plot(x, y)

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

# second plot with x1 and y1 data
plt.plot(x1, y1, '-.')

plt.xlabel("X-axis data")
plt.ylabel("Y-axis data")
plt.title('multiple plots')
plt.show()

Output:

Image

Fill the Area Between Two Lines

Using the pyplot.fill_between() function we can fill in the region between two line plots in the same graph. This will help us in understanding the margin of data between two line plots based on certain conditions. 

Python
import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4])
y = x*2

plt.plot(x, y)

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

plt.plot(x, y1, '-.')
plt.xlabel("X-axis data")
plt.ylabel("Y-axis data")
plt.title('multiple plots')

plt.fill_between(x, y, y1, color='green', alpha=0.5)
plt.show()

Output:

Image

Fill the area between Y and Y1 data corresponding to X-axis data

Line chart in Matplotlib – Python – FAQs

How Do I Make a Line Graph in Matplotlib Python?

Creating a line graph in Matplotlib is straightforward. Here’s a basic example of how to create a simple line graph:

import matplotlib.pyplot as plt

# Data points
x = [0, 1, 2, 3, 4]
y = [0, 2, 4, 6, 8]

# Create a line graph
plt.plot(x, y)

# Adding titles and labels
plt.title('Simple Line Graph')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')

# Show the plot
plt.show()

How to Plot a Line Chart

Plotting a line chart in Python using Matplotlib follows the basic procedure described above. You define your x-values and y-values, use plt.plot() to create the line, and then display the plot with plt.show(). You can also add titles and labels to make the chart more informative.

What are the Different Types of Lines in Matplotlib?

In Matplotlib, you can customize the style of lines in your plots. Here are some of the attributes you can modify:

  • Line Style: Solid ('-'), dashed ('--'), dash-dot ('-.'), dotted (':').
  • Line Width: The width of the line can be specified using the linewidth or lw parameter.
  • Line Color: The color of the line can be specified using the color parameter.

Example of customizing line styles:

plt.plot(x, y, linestyle='--', color='red', linewidth=2)

What are the 7 Steps in Plotting a Line Graph?

Here are the typical steps involved in plotting a line graph using Matplotlib:

  1. Import Matplotlib: Import the matplotlib.pyplot module.
  2. Prepare Data: Define the data points for the x-axis and y-axis.
  3. Create Plot: Use plt.plot() to create the line graph.
  4. Customize Plot: Add customization like line style, markers, colors, etc.
  5. Add Titles and Labels: Include a title for the graph and labels for x and y axes.
  6. Add Legend: If necessary, add a legend to the graph.
  7. Display the Plot: Show the plot using plt.show().

How to Plot a Line in Matplotlib Using Equation

To plot a line using an equation, you can define a function for the equation and then use numpy to generate x-values and compute the corresponding y-values:

import numpy as np
import matplotlib.pyplot as plt

# Define the equation y = mx + b (e.g., y = 2x + 1)
def line_eq(x):
return 2 * x + 1

# Generate x values
x_values = np.linspace(-10, 10, 400) # 400 points from -10 to 10
y_values = line_eq(x_values) # Calculate y values based on the function

# Plotting the line
plt.plot(x_values, y_values, label='y = 2x + 1')

# Customizing the plot
plt.title('Line Graph from Equation')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()

# Show the plot
plt.show()

This method allows you to visualize mathematical functions and relationships easily using Matplotlib.



Previous Article
Next Article

Similar Reads

Line Chart using Plotly in Python
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Line Chart in Plotly Line plot in Plotly is much
4 min read
Donut Chart using Matplotlib in Python
Prerequisites: Pie Chart in matplotlib Donut charts are the modified version of Pie Charts with the area of center cut out. A donut is more concerned about the use of area of arcs to represent the information in the most effective manner instead of Pie chart which is more focused on comparing the proportion area between the slices. Donut charts are
4 min read
Plot a pie chart in Python using Matplotlib
A Pie Chart is a circular statistical plot that can display only one series of data. The area of the chart is the total percentage of the given data. Pie charts are commonly used in business presentations like sales, operations, survey results, resources, etc. as they provide a quick summary. In this article, let's understand how to create pie char
5 min read
Line chart in Pygal
A line chart or line graph is a type of chart which helps to displays the information as a series of all data points called ‘markers’ and those markers are connected straight through line segments. It is a basic type of chart common in many fields which shows ascending or descending in a graph. A line chart is often used to visualize a trend in dat
2 min read
Stacked Line chart in Pygal
Pygal is a Python module that is mainly used to build SVG (Scalar Vector Graphics) graphs and charts. SVG is a vector-based graphics in the XML format that can be edited in any editor. Pygal can create graphs with minimal lines of code that can be easy to understand and write. Stacked line chart A stacked line chart is a line chart in which lines n
1 min read
How to Create time related line chart in Pygal?
Pygal is a Python module that is mainly used to build SVG (Scalar Vector Graphics) graphs and charts. SVG is a vector-based graphics in the XML format that can be edited in any editor. Pygal can create graphs with minimal lines of code that can be easy to understand and write. Time related chart Time-related charts can be plotted using the line cha
2 min read
How to set border for wedges in Matplotlib pie chart?
Pie charts can be used for relative comparison of data. Python offers several data visualization libraries to work with. The Matplotlib library offers different types of graphs and inbuild methods and properties to manipulate the graph. The wedges in the pie chart can be given a border using the wedgeprops attribute of the pie() method of matplotli
3 min read
Radially displace pie chart wedge in Matplotlib
Pie charts are statistical graphs divided into slices that represent different data values and sum up to 100%. Python is one of the most popularly used programming languages for data visualization. Python has multiple data visualization libraries and Matplotlib is one of them. Matplotlib is widely used because of its simplicity and ease of implemen
3 min read
Draw a horizontal bar chart with Matplotlib
Matplotlib is the standard python library for creating visualizations in Python. Pyplot is a module of Matplotlib library which is used to plot graphs and charts and also make changes in them. In this article, we are going to see how to draw a horizontal bar chart with Matplotlib. Creating a vertical bar chart Approach: Importing matplotlib.pyplot
2 min read
How to display the value of each bar in a bar chart using Matplotlib?
In this article, we are going to see how to display the value of each bar in a bar chart using Matplotlib. There are two different ways to display the values of each bar in a bar chart in matplotlib - Using matplotlib.axes.Axes.text() function.Use matplotlib.pyplot.text() function. Example 1: Using matplotlib.axes.Axes.text() function: This functio
2 min read
Plot Multiple Columns of Pandas Dataframe on Bar Chart with Matplotlib
Prerequisites: PandasMatplotlib In this article, we will learn how to plot multiple columns on bar chart using Matplotlib. Bar Plot is used to represent categories of data using rectangular bars. We can plot these bars with overlapping edges or on same axes. Different ways of plotting bar graph in the same chart are using matplotlib and pandas are
2 min read
Display percentage above bar chart in Matplotlib
In this article, we are going to discuss how we can plot a bar chart using the Matplotlib library and display percentages above each bar in the bar chart. For the sake of explanation, we are going to take an example of the runs scored by former Indian Captain MS Dhoni across all the formats, and then we will compare the percentage of runs scored ac
4 min read
Adding value labels on a Matplotlib Bar Chart
Prerequisites: Matplotlib In this article, we are going to Add value labels on a Matplotlib Bar Chart. Bar Chart is the graphical display of data using bars of different heights. We can compare different data's using this bar chart. For plotting the data in Python we use bar() function provided by Matplotlib Library in this we can pass our data as
8 min read
How to Create a Candlestick Chart in Matplotlib?
A candlestick chart, often known as a Japanese candlestick chart, is a financial chart that shows the price movement of stocks, derivatives, and other financial instruments in real-time, there are simply four essential components that must be examined. The open, high, low, and close are the four key elements, the candlestick chart has been used. It
4 min read
Compare two Files line by line in Python
In Python, there are many methods available to this comparison. In this Article, We'll find out how to Compare two different files line by line. Python supports many modules to do so and here we will discuss approaches using its various modules. This article uses two sample files for implementation. Files in use: file.txt file1.txt Method 1: Using
3 min read
Read a file line by line in Python
Prerequisites: Open a file Access modes Close a file Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file. Learning Ef
7 min read
How to Change the Line Width of a Graph Plot in Matplotlib with Python?
Prerequisite : Matplotlib In this article we will learn how to Change the Line Width of a Graph Plot in Matplotlib with Python. For that one must be familiar with the given concepts: Matplotlib : Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on
2 min read
Change grid line thickness in 3D surface plot in Python - Matplotlib
Prerequisites: Matplotlib Using Matplotlib library we can plot the three-dimensional plot by importing the mplot3d toolkit. In this plot, we are going the change the thickness of the gridline in a three-dimensional surface plot. Surface Plot is the diagram of 3D data it shows the functional relationship between the dependent variable (Y), and two i
6 min read
PyQtGraph - Setting Symbol of Line in Line Graph
In this article we will see how we can set symbols of line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A li
3 min read
PyQtGraph - Setting Shadow Pen of Line in Line Graph
In this article, we will see how we can set shadow pen of the line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, et
3 min read
PyQtGraph - Setting Pen of Line in Line Graph
In this article we will see how we can set pen of the line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A li
4 min read
PyQtGraph - Setting Alpha Value of Line in Line Graph
In this article we will see how we can set alpha value of the line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, et
4 min read
PyQtGraph - Clearing the Line in Line Graph
In this article, we will see how we can clear the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A line c
3 min read
PyQtGraph - Getting Data Bounds of the Line in Line Graph
In this article we will see how we can get data bounds of the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, et
4 min read
PyQtGraph - Getting Data of Line in Line Graph
In this article we will see how we can get data of the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A l
3 min read
PyQtGraph - Getting Name of Line in Line Graph
In this article we will see how we can get name of the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A l
4 min read
PyQtGraph - Setting Symbol Pen of Line in Line Graph
In this article we will see how we can set symbol pen of line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) A
4 min read
PyQtGraph - Setting Symbol Size of Line in Line Graph
In this article we will see how we can set symbol size of line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.)
4 min read
PyQtGraph - Getting Pixel Padding of Line in Line Graph
In this article we will see how we can get pixel padding of the line of line graph in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video,
4 min read
PyQtGraph - Setting Symbol Brush of Line in Line Graph
In this article we will see how we can set symbols brush of line in line graph of the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.
3 min read
Practice Tags :