How do I Add Horizontal Lines to Existing Plots in Matplotlib?

Patricia Arquette
Release: 2024-11-22 00:18:12
Original
736 people have browsed it

How do I Add Horizontal Lines to Existing Plots in Matplotlib?

Plotting Horizontal Lines on Existing Figures with axhline

Adding horizontal lines to existing plots is a simple task using Matplotlib. The axhline function creates a horizontal axis line at a specified y-coordinate.

Syntax:

matplotlib.pyplot.axhline(y=y_value, color=color, linestyle=linestyle)
Copy after login

Parameters:

  • y: The y-coordinate of the horizontal line.
  • color: The color of the line.
  • linestyle: The linestyle of the line (e.g., '-', '--', ':').

Example:

To plot a horizontal line at y = 0.5, you can use the following code:

import matplotlib.pyplot as plt

# Create a figure and axes
fig, ax = plt.subplots()

# Add a horizontal line
ax.axhline(y=0.5, color='r', linestyle='-')

# Show the figure
plt.show()
Copy after login

This will produce the following figure:

[Image of a plot with a horizontal line at y = 0.5]

Customizing the Horizontal Line:

You can customize the appearance of the horizontal line by setting the color and linestyle parameters. For example, the following code would plot a dashed blue line at y = 0.7:

import matplotlib.pyplot as plt

# Create a figure and axes
fig, ax = plt.subplots()

# Add a horizontal line
ax.axhline(y=0.7, color='blue', linestyle='--')

# Show the figure
plt.show()
Copy after login

The above is the detailed content of How do I Add Horizontal Lines to Existing Plots in Matplotlib?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template