Home >Backend Development >Python Tutorial >How to Add a Horizontal Line to an Existing Plot in Python?

How to Add a Horizontal Line to an Existing Plot in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 06:41:03382browse

How to Add a Horizontal Line to an Existing Plot in Python?

Plotting a Horizontal Line on an Existing Plot

Adding a horizontal line to an existing plot in Python can be achieved using the axhline (axis horizontal line) function from the matplotlib.pyplot module. This function allows you to draw a line parallel to the x-axis at a specified y-coordinate.

Syntax:

plt.axhline(y=y-coordinate, **kwargs)

Arguments:

  • y: The y-coordinate of the horizontal line.
  • Additional keyword arguments can be passed to customize the line's appearance, such as:

    • color: The color of the line (default: 'black')
    • linestyle: The style of the line (default: 'solid')

Example:

To plot a horizontal line at y = 0.5:

import matplotlib.pyplot as plt

plt.axhline(y=0.5, color='r', linestyle='-')
plt.show()

This will display a graph with a red dashed line drawn horizontally at y = 0.5.

Note: The axhline function only draws a line parallel to the x-axis. If you wish to draw a vertical line parallel to the y-axis, use the axvline function instead.

The above is the detailed content of How to Add a Horizontal Line to an Existing Plot in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn