Plot vertical line python

Draw vertical line matplotlib

In this Python tutorial, we will discuss Draw vertical line matplotlib in python. Here we will cover different examples related to vertical lines using matplotlib. And we will also cover the following topics:

  • Draw vertical line matplotlib
  • Draw vertical dotted line matplotlib
  • Matplotlib draw vertical line with label
  • Matplotlib draw multiple vertical line
  • Plot vertical line matplotlib datetime
  • Matplotlib draw vertical line between two points
  • Plot vertical line segment matplotlib
  • Plot vertical line on histogram matplotlib

Draw vertical line matplotlib

In this section, we learn about how to plot or draw a vertical line in matplotlib in Python. Before starting the topic, firstly we have to understand what is a vertical line or how it looks.

In general, a vertical line is a straight line that goes from top to bottom and vice versa. Or If we talk in coordinates plane, a line parallel to Y-axis is known as a vertical line.

draw vertical line matplotlib

In Python, matplotlib is a popular library used for plotting. It provides different methods to draw a vertical line which we discussed below.

By using plot() method

In matplotlib, the plot() method is used to draw a 2D plot.

The syntax of the plot() method is as given below:

matplotlib.pyplot.plot(x_points, y_points)

The parameters used above are outlined as below:

  • x_points: specify x coordinates points to plot.
  • y_points: specify y coordinates points to plot.

Let’s have a look at an example to clearly understand the concept:

# Import Library import matplotlib.pyplot as plt # Define Data X = [0, 0] Y = [5, 10] # Plot vertical line plt.plot(X,Y) # Show plt.show()
  • In the above example, we import matplotlib.pyplot library.
  • After this, we define data points for plotting. Here we specify the x-axis to 0 because we want to draw a vertical line.
  • Next, we use plt.plot() method for plotting a line and plt.show() method to visualize plot on the user’s screen.

plot vertical line matplotlib

By using vlines()

In matplotlib, the vlines() method is used to draw vertical lines across the axes. Here vlines stand for vertical lines.

The syntax of the vlines() method is as given below:

matplotlib.pyplot.vlines(x, ymin, ymax, colors, linestyles)

The parameters used above are described as below:

  • x: specifies the position on the x-axis to plot the line.
  • ymin and ymax: specify the beginning and end of each line. These attributes are compusolary.
  • colors: specify the color of the line.
  • linestyle: specify the style or type of the line.

Let’s see an example of the vertical line created by using the vlines() method:

# Import Library import matplotlib.pyplot as plt # Plot vertical line plt.vlines(9, 2, 3, color='red') # Show plt.show()
  • In the above example, we import matplotlib.pyplot library.
  • By using plt.vlines() method we plot vertical line. Here we pass x, ymin, ymax, color as an argument and set its value to 9, 2, 3, red respectively.
Читайте также:  Html content type text css

matplotlib plot vertical line

By using axvline()

In matplotlib, the axvline() method is used to add vertical lines to the plot.

The syntax of the axvline() method is as given below:

matplotlib.pyplot.axvline(x, ymin, ymax, color, linestyle)

The above-used parameters are described as below:

  • x: specify position on the x-axis to plot the line.
  • ymin and ymax: specify the starting and ending range of the line.
  • color: specify the color of the line.
  • linestyle: specify the style or type of the line.

Example of axvline() method:

# Import Library import matplotlib.pyplot as plt # Plot vertical line plt.axvline(x=3, ymin=0.25, ymax=0.75) # Show plt.show()

Here we use the axvline() method to draw a vertical line and pass the x, ymin, ymax as a parameter and set its value to 3, 0.25, 0.75 respectively.

matplotlib draw vertical line

Draw vertical dotted line matplotlib

Here we are going to learn how we can draw vertical dotted lines in matplotlib in python. We have to change the line style of lines to make them dotted in style.

Matplotlib.pyplot library provides the parameter linestyle to set types of lines.

Let’s see an example of a vertical dotted line:

# Import Library import matplotlib.pyplot as plt # Plot vertical dotted line plt.axvline(x=5, ymin=0.25, color='red', linestyle='dotted', linewidth=5) # Show plt.show()
  • Here we use the axvline() method to draw a dotted vertical line. We pass parameters x, ymin, color, linestyle, and linewidth.
  • Our main aim is to draw a vertical line that is dotted in nature, so we set linestyle to dotted and increase width of the line by using linewidth parameter.

draw vertical dotted line matplotlib

Matplotlib draw vertical line with label

In this section, we are going to learn how to draw vertical lines with labels. Here we use the axvline() method to draw a vertical line and pass label as a parameter.

The syntax to draw a vertical line with label:

matplotlib.pyplot.axvline(x, ymin, ymax, color, label)
# Import Library import matplotlib.pyplot as plt # Plot vertical line plt.axvline(x=10, linewidth=5, label= 'vertical-line') # Add label plt.legend(loc = 'upper left') # Show plt.show()
  • By using the plt.axvline() method we draw a vertical line and pass the parameter label.
  • Then by using the plt.legend() method we set the location of the label to the upper left.

matplotlib draw vertical line with label

Matplotlib draw multiple vertical line

Here we are going to create multiple vertical lines in matplotlib in python. The methods used to create multiple vertical lines are:

By using axvline()

In matplotlib, by using the axvline() method we can create multiple vertical lines in the plot.

Let’s see an example related to this:

# Import library import matplotlib.pyplot as plt # Vertical line 1 plt.axvline(x = 5, color = 'b') # Vertical line 2 # We also set range of the line plt.axvline(x = 3, ymin = 0.2, ymax = 2, color='red') # Display plt.show()

matplotlib draw multiple vertical line

By using vlines()

In matplotlib, by using the vlines() method we can create multiple vertical lines in the plot.

# Import library import matplotlib.pyplot as plt # Vertical line 1 plt.vlines(x = 5, ymin = 1, ymax = 2, color = 'black') # Vertical line 2 plt.vlines (x = 3, ymin = 1.98, ymax = 1.5, color='red') # Vertical line 3 plt.vlines (x = [1, 2, 3] , ymin = 0.2, ymax = 0.6, color = 'orange') # Vertical line 4 plt.vlines (x = 10, ymin = 0.2, ymax = 2, color='yellow') # Display plt.show()

matplotlib plot multiple vertical line

Plot vertical line matplotlib datetime

Here we draw a vertical line on datetime plot in matplotlib in python.

Читайте также:  Python type function arguments

For this firstly, you have to import the datetime library and after this, by using the axvline() or vlines() method you can draw a vertical line.

Let’s see an example:

# Import Library import matplotlib.pyplot as plt import datetime # Vertical line plt.axvline(datetime.datetime.now()) # Print date and time print(datetime.datetime.now()) # Format date plt.gcf().autofmt_xdate() # Show plt.show()

In the above example we use:

  • datetime.datetime.now() : specify today dates and time
  • autofmt_xdate() : auto formate the dates at x-axis.

plot vertical line matplotlib datetime

Matplotlib draw vertical line between two points

Here we are going to learn how we draw a vertical line between two points or data markers.

Let’s see an example where we connect two points using the vertical line:

# Import Library import matplotlib.pyplot as plt # Define data x = [2, 3, 4, 5] y = [(2, 5), (1, 3), (6, 4), (2, 7)] # Plot plt.plot(x, [i for (i,j) in y], 'co', markersize = 7) plt.plot(x, [j for (i,j) in y], 'mo', markersize = 7) # Vertical line plt.plot((x,x),([i for (i,j) in y], [j for (i,j) in y]),c='red') # Display plt.show()
  • Firstly, we import matplotlib.pyplot library. After this, we define data on the x-axis and y-axis.
  • Then we use plt.plot() method to plot markers or points here we pass xdata point and use for loop for defining ydata point.
  • Now for connecting two points we pass x, y, color as a parameter. Here we set (x,x) for the x-axis point and use for loop for connecting the y-axis point.

matplotlib draw vertical line between two points

Plot vertical line segment matplotlib

Here we are going to see an example where we draw a vertical line segment in the plot in matplotlib.

# Import Library import matplotlib.pyplot as plt import numpy as np # Define Data x = np.arange(0, 15, 0.2) y = np.sin(x) # Plot figure plt.plot(x, y) # Vertical line plt.axvline(x=7.9,color='red') # Title plt.title("Sine Function", fontsize= 15, fontweight='bold') # Generate Plot plt.show()
  • In the above example, we firstly import matplotlib.pyplot, and numpy library.
  • After this, we define data using arange() and sin() method.
  • By using the plt.plot() method we plot a graph.
  • Then use the axvline() method to draw a vertical line.Here we pass x and color as a parameter.
  • plt.title() is used to add a title to the plot and plt.show() method is used to display the plot on the user’s screen.

Plot vertical line segment matplotlib

Plot vertical line on histogram matplotlib

Sometimes programmers want to find the mean of the histogram bars or the function. In that case, we need a vertical line in the histogram to represent mean of the each bar or a function.

Firstly, you have to know how to create a histogram. Let’s see the syntax to create a histogram.

matplotlib.pyplot.hist(x, bins, color, edgecolor, . )

Let’s see an example where we draw a vertical line on the histogram:

# Import Library import numpy as np import matplotlib.pyplot as plt # Define data np.random.random() x = np.random.gamma(15, 1.5, 50) # Plot histogram plt.hist(x, bins=10, color='m', edgecolor='k') # Vertical line plt.axvline(x.mean(), color='k', linestyle='dotted', linewidth=5) # Display plt.show()
  • In the above example, we import matplotlib.pyplot, and numpy packages.
  • Next, we define data using random.gamma() method here we pass the shape, scale, and size as a parameter.
  • Then we use plt.hist() method to draw a histogram for the sample data created.
  • By using plt.axvline() method we draw a vertical line at the mean of the defined sample data.
Читайте также:  Java jackson xml to object

plot vertical line on histogram matplotlib

Also, take a look at some more Matplotlib tutorials.

In this Python tutorial, we have discussed the “Draw vertical line matplotlib” and we have also covered some examples related to it. These are the following topics that we have discussed in this tutorial.

  • Draw vertical line matplotlib
  • Draw vertical dotted line matplotlib
  • Matplotlib draw vertical line with label
  • Matplotlib draw multiple vertical line
  • Plot vertical line matplotlib datetime
  • Matplotlib draw vertical line between two points
  • Plot vertical line segment matplotlib
  • Plot vertical line on histogram matplotlib

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

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

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

Вы можете использовать следующий синтаксис для рисования вертикальной линии в Matplotlib:

import matplotlib.pyplot as plt #draw vertical line at x=2 plt.axvline (x=2) 

В следующих примерах показано, как использовать этот синтаксис на практике со следующими пандами 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 vertical line at x=2 plt.axvline (x=2, color='red', linestyle='--') 

Нарисуйте одну вертикальную линию в Matplotlib

Пример 2. Нарисуйте несколько вертикальных линий

Следующий код показывает, как нарисовать несколько вертикальных линий на графике Matplotlib:

import matplotlib.pyplot as plt #create line plot plt.plot (df.x , df.y ) #add vertical line at x=2 plt.axvline (x=2, color='red', linestyle='--') #add vertical line at x=4 plt.axvline (x=4, color='black', linestyle='-') 

Нарисуйте несколько строк в Matplotlib

Пример 3. Нарисуйте несколько вертикальных линий с легендой

В следующем коде показано, как нарисовать несколько вертикальных линий на графике Matplotlib и добавить легенду, чтобы упростить интерпретацию линий:

import matplotlib.pyplot as plt #create line plot plt.plot (df.x , df.y ) #add vertical line at x=2 plt.axvline (x=2, color='red', linestyle='--', label='First Line') #add vertical line at x=4 plt.axvline (x=4, color='black', linestyle='-', label='Second Line') #add legend plt.legend() 

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

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

Источник

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