RezaOptic
RezaOptic

Reputation: 310

How can draw a line using the x and y coordinates of two points?

I would like to know how to draw a line using the x and y coordinates of two 2-dimensional points. I tried the turtle graphics, but it works using degrees.

Upvotes: 7

Views: 95990

Answers (6)

volent
volent

Reputation: 471

If you are already using turtle you can use a Tkinter canva :

import tkinter
x1, y1, x2, y2 = 10, 20, 30, 40
window = tkinter.Tk()
canva = tkinter.Canvas(window)
line = canva.create_line(x1, y1, x2, y2)
canva.pack()

Upvotes: 4

Steschu
Steschu

Reputation: 126

Just for completeness, you can also use the ImageDraw module of Pillow (Python Image Library / PIL fork). That way you don't need a window and you can save the drawn image into a file instead.

from PIL import Image, ImageDraw

im = Image.new('RGB', (100, 100))

draw = ImageDraw.Draw(im)
draw.line((0, 0) + im.size, fill=128)
draw.line((0, im.size[1], im.size[0], 0), fill=128)

im.save('test.png')

Upvotes: 3

cdlane
cdlane

Reputation: 41925

I tried the turtle graphics, but it works using degrees.

Your premise doesn't hold -- turtle can do it, no degrees needed:

import turtle

point1 = (50, 100)
point2 = (150, 200)

turtle.penup()
turtle.goto(point1)
turtle.pendown()
turtle.goto(point2)

turtle.hideturtle()
turtle.exitonclick()

Upvotes: 10

Nick is tired
Nick is tired

Reputation: 7056

You could make use of pygame depending on what you are doing it for as it allows a similar:

line(Surface, color, (x1,y1), (x2,y2), width)

For Example, when the environment has been set up:

pygame.draw.line(screen, (255,0,255), (20,20), (70,80), 2)

can draw:

Test line

Upvotes: 6

efirvida
efirvida

Reputation: 4875

Depending of your needs for plotting you can use matplotlib

import matplotlib.pyplot as plt
plt.plot([x1,x2],[y1,y2])
plt.show()

Upvotes: 13

Rob S.
Rob S.

Reputation: 1156

You could calculate the angle from the 4 points using the following formula

angle = arctan((y2-y1)/(x2-x1))

Just a warning, depending on the math library you use, this will probably output in radians. However you can convert radians to degrees using the following formula.

deg = rad * (180/pi)

Upvotes: 2

Related Questions