How do you draw a line between two points in python?


To create line segments between two points in matplotlib, we can take the following steps

  • Set the figure size and adjust the padding between and around the subplots.
  • To make two points, create two lists.
  • Extract x and y values from point1 and point2.
  • Plot x and y values using plot() method.
  • Place text for both the points.
  • To display the figure, use show() method.

Example

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
point1 = [1, 2]
point2 = [3, 4]
x_values = [point1[0], point2[0]]
y_values = [point1[1], point2[1]]
plt.plot(x_values, y_values, 'bo', linestyle="--")
plt.text(point1[0]-0.015, point1[1]+0.25, "Point1")
plt.text(point2[0]-0.050, point2[1]-0.25, "Point2")
plt.show()

Output

How do you draw a line between two points in python?

How do you draw a line between two points in python?

Updated on 02-Jun-2021 08:39:05

  • Related Questions & Answers
  • How do I find the intersection of two line segments in Matplotlib?
  • Check if two line segments intersect
  • Shading an area between two points in a Matplotlib plot
  • How do you create a legend for a contour plot in Matplotlib?
  • Draw a curve connecting two points instead of a straight line in matplotlib
  • How do you improve Matplotlib image quality?
  • How do you add two lists in Java?
  • Number of Integral Points between Two Points in C++
  • How do you create nested dict in Python?
  • How do you create a list in Java?
  • How to create a line chart using Matplotlib?
  • How do you OR two MySQL LIKE statements?
  • How do you pass a command line argument in Java program?
  • How do you create a clickable Tkinter Label?
  • How do you create an empty list in Java?

I know there is another very similar question, but I could not extract the information I need from it.

plotting lines in pairs

I have 4 points in the (x,y) plane: x=[x1,x2,x3,x4] and y=[y1,y2,y3,y4]

x=[-1 ,0.5 ,1,-0.5]
y=[ 0.5,  1, -0.5, -1]

Now, I can plot the four points by doing:

import matplotlib.pyplot as plt

plt.plot(x,y, 'ro')
plt.axis('equal')
plt.show()

But, apart from the four points, I would like to have 2 lines:

1) one connecting (x1,y1) with (x2,y2) and 2) the second one connecting (x3,y3) with (x4,y4).

This is a simple toy example. In the real case I have 2N points in the plane.

How can I get the desired output: for points with two connecting lines ?

Thank you.

How do you draw a line between two points in python?

8-Bit Borges

9,17925 gold badges85 silver badges168 bronze badges

asked Feb 12, 2016 at 13:08

I think you're going to need separate lines for each segment:

import numpy as np
import matplotlib.pyplot as plt

x, y = np.random.random(size=(2,10))

for i in range(0, len(x), 2):
    plt.plot(x[i:i+2], y[i:i+2], 'ro-')

plt.show()

(The numpy import is just to set up some random 2x10 sample data)

How do you draw a line between two points in python?

answered Feb 12, 2016 at 13:23

xnxxnx

23.5k9 gold badges65 silver badges104 bronze badges

2

You can just pass a list of the two points you want to connect to plt.plot. To make this easily expandable to as many points as you want, you could define a function like so.

import matplotlib.pyplot as plt

x=[-1 ,0.5 ,1,-0.5]
y=[ 0.5,  1, -0.5, -1]

plt.plot(x,y, 'ro')

def connectpoints(x,y,p1,p2):
    x1, x2 = x[p1], x[p2]
    y1, y2 = y[p1], y[p2]
    plt.plot([x1,x2],[y1,y2],'k-')

connectpoints(x,y,0,1)
connectpoints(x,y,2,3)

plt.axis('equal')
plt.show()

How do you draw a line between two points in python?

Note, that function is a general function that can connect any two points in your list together.

To expand this to 2N points, assuming you always connect point i to point i+1, we can just put it in a for loop:

import numpy as np
for i in np.arange(0,len(x),2):
    connectpoints(x,y,i,i+1)

In that case of always connecting point i to point i+1, you could simply do:

for i in np.arange(0,len(x),2):
    plt.plot(x[i:i+2],y[i:i+2],'k-')

answered Feb 12, 2016 at 13:21

tmdavisontmdavison

59.8k12 gold badges167 silver badges150 bronze badges

1

I realize this question was asked and answered a long time ago, but the answers don't give what I feel is the simplest solution. It's almost always a good idea to avoid loops whenever possible, and matplotlib's plot is capable of plotting multiple lines with one command. If x and y are arrays, then plot draws one line for every column.

In your case, you can do the following:

x=np.array([-1 ,0.5 ,1,-0.5])
xx = np.vstack([x[[0,2]],x[[1,3]]])
y=np.array([ 0.5,  1, -0.5, -1])
yy = np.vstack([y[[0,2]],y[[1,3]]])
plt.plot(xx,yy, '-o')

Have a long list of x's and y's, and want to connect adjacent pairs?

xx = np.vstack([x[0::2],x[1::2]])
yy = np.vstack([y[0::2],y[1::2]])

Want a specified (different) color for the dots and the lines?

plt.plot(xx,yy, '-ok', mfc='C1', mec='C1')

How do you draw a line between two points in python?

answered May 28, 2020 at 20:49

JinjerJohnJinjerJohn

3432 silver badges5 bronze badges

1

Use the matplotlib.arrow() function and set the parameters head_length and head_width to zero to don't get an "arrow-end". The connections between the different points can be simply calculated using vector addition with: A = [1,2], B=[3,4] --> Connection between A and B is B-A = [2,2]. Drawing this vector starting at the tip of A ends at the tip of B.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')


A = np.array([[10,8],[1,2],[7,5],[3,5],[7,6],[8,7],[9,9],[4,5],[6,5],[6,8]])


fig = plt.figure(figsize=(10,10))
ax0 = fig.add_subplot(212)

ax0.scatter(A[:,0],A[:,1])


ax0.arrow(A[0][0],A[0][1],A[1][0]-A[0][0],A[1][1]-A[0][1],width=0.02,color='red',head_length=0.0,head_width=0.0)
ax0.arrow(A[2][0],A[2][1],A[9][0]-A[2][0],A[9][1]-A[2][1],width=0.02,color='red',head_length=0.0,head_width=0.0)
ax0.arrow(A[4][0],A[4][1],A[6][0]-A[4][0],A[6][1]-A[4][1],width=0.02,color='red',head_length=0.0,head_width=0.0)


plt.show()

How do you draw a line between two points in python?

answered May 24, 2018 at 12:55

How do you draw a line between two points in python?

2Obe2Obe

3,3025 gold badges27 silver badges52 bronze badges

With the code below you can create multiple lines by connecting points thanks to their coordinates :

import matplotlib.pyplot as plt

# 1st line
point_1 = [1,3]
point_2 = [2,6]

# 2nd line
point_3 = [4,6]
point_4 = [1,2]

x_values = [[point_1[0], point_3[0]],[point_2[0], point_4[0]]]
y_values = [[point_1[1], point_3[1]],[point_2[1], point_4[1]]]

plt.plot(x_values, y_values, 'red')
plt.show()

Result

How do you draw a line between two points in python?

answered Jan 30 at 0:02

How do you draw a line between two points in python?

Julien JmJulien Jm

1,9802 gold badges19 silver badges26 bronze badges

I would prefer LineCollection in matplotlib. See following minimum code:

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

x = np.arange(100)
# Here are many sets of y to plot vs. x
ys = x[:50, np.newaxis] + x[np.newaxis, :]

segs = np.zeros((50, 100, 2))
segs[:, :, 1] = ys
segs[:, :, 0] = x

# We need to set the plot limits.
fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
ax.set_xlim(x.min(), x.max())
ax.set_ylim(ys.min(), ys.max())

line_segments = LineCollection(segs)
ax.add_collection(line_segments)

A more detailed example can be found here.

answered Sep 11, 2021 at 1:48

JiadongJiadong

1,46413 silver badges32 bronze badges

How do I make a line in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.

How do you draw a horizontal line in Python?

In matplotlib, if you want to draw a horizontal line with full width simply use the axhline() method. You can also use the hlines() method to draw a full-width horizontal line but in this method, you have to set xmin and xmax to full width.

Which function is used to draw line between the two given points?

segment() function in R Language is used to draw a line segment between to particular points.

How do you draw two lines in python?

Line plot: Line plots can be created in Python with Matplotlib's pyplot library..
y = x..
x = y..
y = sin(x).
y = cos(x).