Plotting a Line Curve (Python)

vegaseat 0 Tallied Votes 2K Views Share

You can use the Tkinter canvas and the canvas.create_line() function to draw a line plot of a mathematical function. The canvas.create_line() function accepts a list of x, y points that you can create within a for loop. The resulting plot is centered and can be stretched along the x and y axis to suit your needs.

# plot a function like y = sin(x) with Tkinter canvas and line
# tested with Python24  by     vegaseat      25oct2006

from Tkinter import *
import math

root = Tk()
root.title("Simple plot using canvas and line")

width = 400
height = 300
center = height//2
x_increment = 1
# width stretch
x_factor = 0.04
# height stretch
y_amplitude = 80

c = Canvas(width=width, height=height, bg='white')
c.pack()

str1 = "sin(x)=blue  cos(x)=red"
c.create_text(10, 20, anchor=SW, text=str1)

center_line = c.create_line(0, center, width, center, fill='green')

# create the coordinate list for the sin() curve, have to be integers
xy1 = []
for x in range(400):
    # x coordinates
    xy1.append(x * x_increment)
    # y coordinates
    xy1.append(int(math.sin(x * x_factor) * y_amplitude) + center)

sin_line = c.create_line(xy1, fill='blue')

# create the coordinate list for the cos() curve
xy2 = []
for x in range(400):
    # x coordinates
    xy2.append(x * x_increment)
    # y coordinates
    xy2.append(int(math.cos(x * x_factor) * y_amplitude) + center)

cos_line = c.create_line(xy2, fill='red')

root.mainloop()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.