- How to plot an horizontal line with Python in a Matplotlib or Seaborn chart?
- Preparation
- Python horizontal line plotting using Matplotlib
- Customizing the Matplotlib axhline example
- Plotting multiple lines
- Drawing grid lines
- Как нарисовать горизонтальную линию в Matplotlib (с примерами)
- Пример 1. Нарисуйте одну горизонтальную линию
- Пример 2. Нарисуйте несколько горизонтальных линий
- Пример 3. Нарисуйте несколько горизонтальных линий с легендой
- How to Plot a Horizontal Line in Matplotlib Python
- How to Plot a Horizontal Line in Matplotlib Python
- Matplotlib Horizontal Line Syntax
- How to plot a Single Horizontal Line in Matplotlib Python
- Example (1):
- Output:
- Explanation:
- How to plot Multiple Horizontal Lines in Matplotlib Python
- Example (2):
- Output:
- Adding Legend to the Graph
- Example (3):
- Output:
- Explanation:
- Conclusion
- Rishikesh Kumar
How to plot an horizontal line with Python in a Matplotlib or Seaborn chart?
In today’s quick Data visualization tutorial, we will show you how you can easily draw horizontal lines in Python plots that run in parallel to the X axis. We’ll use a bar plot as an example, but you can obviously apply the same logic for other charts such as scatter, histogram, lien plots etc’. Once we render the line over our chart, we’ll demonstrate some simple customization options.
Preparation
We’ll start by defining some dummy data for our chart by leveraging the numpy library.
import numpy as np import matplotlib.pyplot as plt np.random.seed(10) x = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'] y = np.random.randint(75,100,5)
Python horizontal line plotting using Matplotlib
We’ll first use Matplotlib to render our plot:
fig, ax= plt.subplots(figsize=(9,5)) ax.bar(x, height=y); # Now we'll use the plt.axhline method to render the horizontal line at y=81 fig, ax= plt.subplots(figsize=(9,5)) ax.bar(x, height=y); ax.axhline(y=81);
Customizing the Matplotlib axhline example
We’ll customize the line style by defining custom color, marker style, line style and width as shown below:
fig, ax= plt.subplots(figsize=(9,5)) ax.bar(x, height=y); ax.axhline(y=81, color='green', marker='o', linestyle='--', linewidth = 5);
Plotting multiple lines
To add multiple lines to the chart, we’ll simply invoke axhline as needed.
fig, ax= plt.subplots(figsize=(9,5)) ax.bar(x, height=y); ax.axhline(y=81, color='green', marker='o', linestyle='--', linewidth = 5); ax.axhline(y=61, color='red', marker='o', linestyle='--', linewidth = 5);
Drawing grid lines
If we want to easily draw gridlines in the background of our chart we can call plt.grid method
Note: if you prefer the grid line to be displayed behind the chart, just use the zorder parameter.
fig, ax= plt.subplots(figsize=(9,5)) ax.bar(x, height=y, zorder=10); ax.grid(zorder=0)
Vertical lines plotting will be covered in our next tutorial.
Как нарисовать горизонтальную линию в Matplotlib (с примерами)
Вы можете использовать следующий синтаксис для рисования горизонтальной линии в Matplotlib:
import matplotlib.pyplot as plt #draw vertical line at y=10 plt.axhline (y=10)
В следующих примерах показано, как использовать этот синтаксис на практике со следующими пандами DataFrame:
import pandas as pd #create DataFrame df = pd.DataFrame() #view DataFrame df x y 0 1 5 1 2 7 2 3 8 3 4 15 4 5 26 5 6 39 6 7 45 7 8 40
Пример 1. Нарисуйте одну горизонтальную линию
Следующий код показывает, как нарисовать одну горизонтальную линию на графике Matplotlib:
import matplotlib.pyplot as plt #create line plot plt.plot (df.x , df.y ) #add horizontal line at y=10 plt.axhline (y=10, color='red', linestyle='--')
Пример 2. Нарисуйте несколько горизонтальных линий
Следующий код показывает, как нарисовать несколько горизонтальных линий на графике Matplotlib:
import matplotlib.pyplot as plt #create line plot plt.plot (df.x , df.y ) #add horizontal line at y=10 plt.axhline (y=10, color='red', linestyle='--') #add horizontal line at y=30 plt.axhline (y=30, color='black', linestyle='-')
Пример 3. Нарисуйте несколько горизонтальных линий с легендой
В следующем коде показано, как нарисовать несколько горизонтальных линий на графике Matplotlib и добавить легенду, чтобы упростить интерпретацию линий:
import matplotlib.pyplot as plt #create line plot plt.plot (df.x , df.y ) #add horizontal line at y=10 plt.axhline (y=10, color='red', linestyle='--', label='First Line') #add horizontal line at y=30 plt.axhline (y=30, color='black', linestyle='-', label='Second Line') #add legend plt.legend()
Примечание. Полный список цветов и стилей линий, которые можно применять к горизонтальным линиям, см. в документации Matplotlib .
How to Plot a Horizontal Line in Matplotlib Python
Rishikesh Kumar
How to Plot a Horizontal Line in Matplotlib Python
In this article, we will learn how to plot a horizontal line in the matplotlib python library. Matplotlib is one of the most popular libraries available in python to visualize data.
How to plot horizontal line in Matplotlib? To plot a horizontal line in Matplotlib, use the axhline() function. This function creates a horizontal line across the plot with specified parameters such as y-position, color, and linewidth.
Matplotlib Horizontal Line Syntax
matplotlib.pyplot.axhline(y, color, xmin, xmax, linestyle)
- y: This is an integer that defines the position on the Y-axis to plot the line.
- xmin and xmax: Range in which line is plotted.
- color: Defines the color for the line; it accepts a string. eg ‘r’ or ‘b’.
- lifestyle: It defines the type of line and accepts a string. like ‘-‘, ‘–’, ‘-.’, ‘:’, ‘None’, ‘ ‘, “, ‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’.
How to plot a Single Horizontal Line in Matplotlib Python
To draw a single line, we can use the axhline() function, which is available in the matplotlib library of python. This is a plotting 1module used for drawing a horizontal line. Below is the example code with the corresponding output.
Example (1):
import matplotlib.pyplot as plt plt.axhline(y = 0.52, color = 'b', linestyle = 'solid') plt.axhline(y = 0.84, color = 'red', linestyle = 'dashdot') plt.axhline(y = 0.37, color = 'green', linestyle = 'dotted')
Output:
Explanation:
- First, we import the matplotlib library using the following command:
import matplotlib.pyplot as plt
Since we need to use the library often, we have imported the big-name -matplotlib. pyplot as plt for convenience. - plt.axline() function will create a horizontal line in the graph.y=0.5 defines the value of y for all the values of x in x axis.
- The color parameter defines the color of the line in the graph. The linestyle parameter defines the style of the scatter points to be used in the graph.
- Finally, the plt.show() function will help to display the graph.
Note: We have a complete study about all types of bar charts in the matplotlib library that you can refer to them from here: Python Matplotlib Bar Chart
How to plot Multiple Horizontal Lines in Matplotlib Python
We can draw multiple lines in a graph using the same axhline() function; we need to define the axis points to multiple axhline() functions in the same plan.
Example (2):
import matplotlib.pyplot as plt plt.axhline(y = .53, xmin = 0.35, xmax = 0.19) plt.axhline(y = 4, color = 'blue', linestyle = '--') plt.axhline(y = 2, color = 'red', linestyle = ':') plt.axhline(y = 1, color = 'purple', linestyle = 'dotted') plt.xlabel('x - axis') plt.ylabel('y - axis') plt.show()
Output:
Adding Legend to the Graph
Adding a legend to the graph can make the graph more readable. We can add a legend using the legend() function available in the matplotlib library. See the below code:
Example (3):
import matplotlib.pyplot as plt plt.axhline(y = 0.5, xmin = 0.25, xmax = 0.9) plt.axhline(y = 1, color = 'brown',xmin = 0.35, linestyle = ':', label = "brown line") plt.axhline(y = 2, color = 'black', linestyle = '--', label = "black line") plt.axhline(y = 2.5, color = 'purple', linestyle = 'dashed', label = "purple line") plt.axhline(y = 3, color = 'yellow', linestyle = 'dashed', label = "yellow line") plt.axhline(y = 3.5, color = 'purple', linestyle = 'dashed', label = "red line") plt.xlabel('numbers') plt.ylabel('scaling') plt.legend(loc = 'upper right') plt.title("Illustrating the horizontal color") plt.show()
Output:
Explanation:
- For convenience, we have imported the matplotlib. pyplot as plt.
- plt.axhile() function will create the line next. Different line styles are taken in the example. The color attribute is used to segregate the lines in the graphs.
- plt.xlabel() is used to mark what data is carried on the x-axis, and plt. label() is used to mark what data is carried on the y axis.
- Finally, the plt.show() function will help to display the graph.
Conclusion
So in this way, we can plot a horizontal line using the matplotlib library’s axhline() function. We can also plot more than one line in a single plot; we must define the axis points inside the axhline() function.
Rishikesh Kumar
I’m Rishikesh kumar, recently completed B.tech in Computer Science & Engineering. I have deep knowledge of C/C++, Java, Python and SQL and have done various projects using them. I have also done few internships and training from reputed organization like IBM & IIT Kharagpur. I always love learning more about Computer Technology, Machine Learning, Data science and mobile technology as they are my specialization. Apart from my academic knowledge, I’m also a passionate content writer experienced in delivering quality content in the field of technology, education and travel based industries. Being a virtuous, diligent worker and a reliable professional would make me an asset to your organization.