Horizontal line in plot python

Как нарисовать горизонтальную линию в Matplotlib (с примерами)

Как нарисовать горизонтальную линию в 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='--') 

Как нарисовать горизонтальную линию в Matplotlib

Пример 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='-') 

Несколько горизонтальных линий в Matplotlib

Пример 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 с легендой

Примечание. Полный список цветов и стилей линий, которые можно применять к горизонтальным линиям, см. в документации Matplotlib .

Источник

Читайте также:  Print list line by line python

Plot Horizontal Line in Python

Plot Horizontal Line in Python

  1. Horizontal Line in Python
  2. Use the plot() Function in Python
  3. Use the hlines() Function in Python
  4. Use the axhline() Function in Python
  5. Dotted Horizontal Line in Python
  6. Horizontal Line With Label in Python
  7. Multiple Horizontal Line Matplotlib

We will introduce how to create a horizontal line in Python. We will also introduce the Matplotlib library in Python.

Horizontal Line in Python

A horizontal line is any straight line that drives from left to right or right to left. When we see it in a coordinate plane, it is a line parallel to the x-axis.

  1. Plotting horizontal line by the plot() function.
  2. Plotting horizontal lines by the hlines() function.
  3. Plotting horizontal line by the axhline() function.

Use the plot() Function in Python

When our goal is to produce 2D plots, we can use the Plot() function. X points are x-axis points towards the plot, and Y points are y-axis points.

# python import matplotlib.pyplot as plotLine  xAxis = [3, 5, 7, 9] yAxis = [0, 0, 0, 0] plotLine.plot(xAxis,yAxis) plotLine.show() 

horizontal line in python using plot() function

First, we imported the matplotlib.pyplot library, then outlined the data points we wanted to plot. In this example, we stated the y-axis points to be 0 because our goal is to draw a horizontal line.

We apply the plotLine.plot() function to draw a line, and for visual purposes, we have used plotLine.show() .

Use the hlines() Function in Python

When we want to draw a horizontal line across the axes, we use the hlines() function. This function will simplify our task.

# python hlines(Yaxis, XaxisStart, XaxisEnd, lineColor, lineStyle) 

Here, four parameters are used, Yaxis will denote the position on the y-axis when we need to plot a line. XaxisStart and XaxisEnd indicate where the line starts and where it will end.

The lineColor will add the required colors to the line, and the lineStyle will add the style or type of the line we specified.

# python import matplotlib.pyplot as plotLine  plotLine.hlines(3, 5, 10, color='blue') plotLine.show() 

horizontal line in python using hline() function

We used the matplotlib.pyplot library to create a horizontal line with the help of the hlines() function. As an argument, we have passed the values and got the result as shown above.

Читайте также:  This operator in cpp

Use the axhline() Function in Python

The axhline() function is designed to draw horizontal lines to the plot. The axhline() function has similar parameters as in hlines() function.

# python import matplotlib.pyplot as plotLine  plotLine.axhline(y=1.3, xmin=0.2, xmax=0.7) plotLine.show() 

horizontal line in python using axhline() function

We have drawn a horizontal line and authorized the y , xmin , and xmax as parameters and fixed them as 1.3, 0.2, and 0.7.

Dotted Horizontal Line in Python

Matplotlib library also allows us to have a dotted line. When we need a dotted horizontal line, we have to change the line style to a dotted line, which will do the trick for us.

The Matplotlib.pyplot library offers the linestyle parameter to set the line type.

# python import matplotlib.pyplot as plotLine  plotLine.axhline(y=1.3, xmin=0.2, xmax=0.7, linestyle='dotted') plotLine.show() 

dotted horizontal line in python using axhline() function

The axhline() function have four parameters y , xmin , xmax , and linestyle . Our goal is to achieve a horizontal line dotted in style, so we fixed linestyle to dotted.

Horizontal Line With Label in Python

We can also achieve a horizontal line with a label with the help of the axhline() function. We have to set the label as a parameter.

# python import matplotlib.pyplot as plotLine  plotLine.axhline(y=1.3, xmin=0.2, xmax=0.7, label= 'Line Label') plotLine.legend(loc='upper left') plotLine.show() 

horizontal line with label in python using axhline() function

We can easily create a label for the horizontal line by using the label parameter. We can define the label’s location using another function, legend() .

Multiple Horizontal Line Matplotlib

We can also achieve multiple horizontal lines in matplotlib in Python. There are two methods available by which we can achieve our goal, using the axhline() method or by using the hlines() method.

Axhline() method allows us to obtain multiple horizontal lines in the plot.

# python import matplotlib.pyplot as plotLine  plotLine.axhline(y=1.3, xmin=0.2, xmax=0.7, label= 'Blue Line Label') plotLine.legend(loc='upper left') plotLine.axhline(y=1.8, xmin=0.6, xmax=0.9, label= 'Red Line Label', color="red") plotLine.legend(loc='upper left') plotLine.axhline(y=1.5, xmin=0.5, xmax=0.9, label= 'Yellow Line Label', color="yellow") plotLine.legend(loc='upper left') plotLine.show() 

multiple horizontal line in python using axhline() function

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

Читайте также:  Что такое рантайм java

Источник

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.

Источник

Оцените статью