Open In App

Line chart in Matplotlib – Python

Last Updated : 13 Aug, 2024
Summarize
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:

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:     

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:

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:

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:

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.



Next Article

Similar Reads

Practice Tags :
three90RightbarBannerImg
  翻译: