How to draw line using coordinates in Python

In this tutorial, I am going to discuss how to draw a line using coordinates in Python. In Python, I am going to use matplotlib for the drawing line in Python.

Draw a line using coordinates in Python


Matplotlib is a graphical library used for plotting or visualizations of data in Python. It is generally used for plotting arrays. It is a multi-platform and multi-purpose data plotting library.

Matplotlib was introduced in the year 2002 by John Hunter. matplotlib has several plotting techniques like line, histogram, bar, scatter, etc.

First thing you’re going to be able to import matplotlib library, for instance

import matplotlib.pyplot as plt

Let’s walk through a simple example using two NumPy arrays

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1,10,20)
y1 = x
y2 = x**2
plt.plot(x,y1)
plt.show() #output shown in figure_1
plt.plot(x,y2)
plt.show   #output shown in figure_2
  • linspace is a method of NumPy module used for creating a sequence of numbers as a NumPy array.
  • Here plot method is used for plotting and the show is for showing output to the user.
The output of above code shown in figure_1 and figure_2 just bellow :-

How to draw line using coordinates in Python

and

How to draw line using coordinates in Python

Now if there are given two coordinates to draw a line, firstly we have to make two different arrays for the values of x and y respectively and use that x and y value array in the plot function of matplotlib to draw the line for the corresponding coordinates.

For example consider two points x1, y1 as (1,2) and x2,y2 as (5,9) respectively. So now we have to keep all x value in one array and all y value in another array(sample code is given below).

import matplotlib.pyplot as plt
import numpy as np

#coordinate of first point
x1 = 1
y1=2
#coordinate of first point
x2=5
y2=9
#combine all x value and y value separately 
x_values = [x1,x2]
y_values = [y1,y2]
#now plot x_values and y_values
plt.plot(x_values,y_values)
plt.show() #output shown in figure_3
The output of above code shown in figure_3:-

How to draw line using coordinates in Python

I can suggest you use matplotlib for different plotting purposes because matplotlib has several plotting techniques like line, histogram, bar, scatter, etc.

Also read:
command-line argument in Python

Leave a Reply

Your email address will not be published. Required fields are marked *