Python построение графиков tkinter

Рисование графиков. Python. Tkinter

Это моя первая статья и я хотел бы рассказать о том как написать простейшую программу по рисованию графиков функций.
Статья ориентирована на новичков!
Начнем с того, что наша функция будет иметь вид:
y = c(x)
Где c(x) — это выражение от одной переменной «x».
Сразу считаем её.

Считать значение функции мы будем функцией eval().
Подключим нужные нам библиотеки.

from math import * from tkinter import * f = input('f(x):') 

Теперь надо нарисовать оси координат.

from math import * from tkinter import * f = input('f(x):') root = Tk() canv = Canvas(root, width = 1000, height = 1000, bg = "lightblue", cursor = "pencil") canv.create_line(500,1000,500,0,width=2,arrow=LAST) canv.create_line(0,500,1000,500,width=2,arrow=LAST) canv.pack() root.mainloop() 

Для пересчета значений функции в разных точках я брал 16000 точек на оси X.
Для каждой из них мы считаем значение «y».
Нарисуем овалы с координатами (x, y, x + 1, y + 1).
Овалы, как вы уже, наверное, поняли, — это просто точки на нашем графике.
Перебираем эти точки.

from math import * from tkinter import * f = input('f(x):') root = Tk() canv = Canvas(root, width = 1000, height = 1000, bg = "white") canv.create_line(500,1000,500,0,width=2,arrow=LAST) canv.create_line(0,500,1000,500,width=2,arrow=LAST) First_x = -500; for i in range(16000): x = First_x + (1 / 16) * i new_f = f.replace('x', str(x)) y = -eval(new_f) + 500 x += 500 canv.create_oval(x, y, x + 1, y + 1, fill = 'black') canv.pack() root.mainloop() 

Итак, мы уже умеем выводить оси координат и график функции на отрезке от -500 до 500.

Но если мы введем функцию, которая не определена в какой — нибудь из проверяемых точек, или она содержит ошибку, то наша программа вылетит с ошибкой, это не есть здорово.
Для того, чтобы исправить это, усовершенствуем наш код.
И разметим наши оси.

from math import * from tkinter import * f = input('f(x):') root = Tk() canv = Canvas(root, width = 1000, height = 1000, bg = "white") canv.create_line(500,1000,500,0,width=2,arrow=LAST) canv.create_line(0,500,1000,500,width=2,arrow=LAST) First_x = -500; for i in range(16000): if (i % 800 == 0): k = First_x + (1 / 16) * i canv.create_line(k + 500, -3 + 500, k + 500, 3 + 500, width = 0.5, fill = 'black') canv.create_text(k + 515, -10 + 500, text = str(k), fill="purple", font=("Helvectica", "10")) if (k != 0): canv.create_line(-3 + 500, k + 500, 3 + 500, k + 500, width = 0.5, fill = 'black') canv.create_text(20 + 500, k + 500, text = str(k), fill="purple", font=("Helvectica", "10")) try: x = First_x + (1 / 16) * i new_f = f.replace('x', str(x)) y = -eval(new_f) + 500 x += 500 canv.create_oval(x, y, x + 1, y + 1, fill = 'black') except: pass canv.pack() root.mainloop() 

Теперь готово.
Получилась примитивная рисовала графиков.
image
image
image

Читайте также:  Set value using javascript

Источник

Tkinter Matplotlib

Summary: in this tutorial, you’ll learn how to display a graph from the Matplotlib library on a Tkinter application.

Display a bar chart from matplotlib in Tkinter applications

Matplotlib is a third-party library for creating professional visualizations in Python. Since Matplotlib is a third-party library, you need to install it before use.

To install the matplotlib package, you can use the following pip command:

pip install matplotlibCode language: Python (python)

The following program uses the matplotlib to create a bar chart that shows the top five programming languages by popularity.

import tkinter as tk import matplotlib matplotlib.use('TkAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import ( FigureCanvasTkAgg, NavigationToolbar2Tk ) class App(tk.Tk): def __init__(self): super().__init__() self.title('Tkinter Matplotlib Demo') # prepare data data = < 'Python': 11.27, 'C': 11.16, 'Java': 10.46, 'C++': 7.5, 'C#': 5.26 > languages = data.keys() popularity = data.values() # create a figure figure = Figure(figsize=(6, 4), dpi=100) # create FigureCanvasTkAgg object figure_canvas = FigureCanvasTkAgg(figure, self) # create the toolbar NavigationToolbar2Tk(figure_canvas, self) # create axes axes = figure.add_subplot() # create the barchart axes.bar(languages, popularity) axes.set_title('Top 5 Programming Languages') axes.set_ylabel('Popularity') figure_canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) if __name__ == '__main__': app = App() app.mainloop()Code language: Python (python)

Tkinter Matplotlib

First, import the matplotlib module

import matplotlibCode language: Python (python)

and call the use() function to tell which backend the matplotlib will use:

matplotlib.use('TkAgg')Code language: Python (python)

In this case, we use TkAgg backend, which is made to integrate into Tkinter.

Second, import the following Figure , FigureCanvasTkAgg , and NavigationToolbar2Tk classes:

from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import ( FigureCanvasTkAgg, NavigationToolbar2Tk )Code language: Python (python)

The Figure class represents the drawing area on which matplotlib charts will be drawn.

The FigureCanvasTkAgg class is an interface between the Figure and Tkinter Canvas .

The NavigationToolbar2Tk is a built-in toolbar for the figure on the graph.

Third, prepare the data for showing on the bar chart:

data = < 'Python': 11.27, 'C': 11.16, 'Java': 10.46, 'C++': 7.5, 'C#': 5.26 > languages = data.keys() popularity = data.values()Code language: Python (python)

The data is a dictionary with the keys are the programming languages and values are their popularity in percentage.

Fourth, create a Figure to hold the chart:

figure = Figure(figsize=(6, 4), dpi=100)Code language: Python (python)

The Figure object takes two arguments: size in inches and dots per inch (dpi). In this example, it creates a 600×400 pixel figure.

Fifth, create a FigureCanvasTkAgg object that connects the Figure object with a Tkinter’s Canvas object:

figure_canvas = FigureCanvasTkAgg(figure, self)Code language: Python (python)

Note that the FigureCanvasTkAgg object is not a Canvas object but contains a Canvas object.

Sixth, create a matplotlib ‘s built-in toolbar:

NavigationToolbar2Tk(figure_canvas, self)Code language: Python (python)

Seventh, add a subplot to the figure and return the axes of the subplot:

axes = figure.add_subplot()Code language: Python (python)

Eighth, create a bar chart by calling the bar() method of the axes and passing the languages and popularity into it. Also, set the title and the label of the y-axis:

axes.bar(languages, popularity) axes.set_title('Top 5 Programming Languages') axes.set_ylabel('Popularity')Code language: Python (python)

Finally, place the chart on the Tkinter’s root window:

figure_canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)Code language: Python (python)

Summary

Источник

Using Tkinter and Matplotlib

Recently I was working on a project in which I needed to quickly visualize groups of 2D data points. As the project was in Python, I thought the well-established libraries Tkinter and matplotlib would be useful for this task. Unfortunately, I had to hunt through many sources to figure out how to use these two libraries together, so I am writing this blog post to help others who may have similar needs.

Below is the result from our project:

Data visualization

As you can see we have displayed three groups of data points, each in a different color.

First we will look at setting up the matplotlib environment in Tkinter . Here is a minimal set of necessary import statements.

from tkinter import * from tkinter.ttk import * import matplotlib matplotlib.use("TkAgg") from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg 

For the purposes of this blog post we will create a window with nothing but the matplotlib canvas to make things simpler. Suppose our Tkinter application consists of nothing but the following:

Now we can start creating the matplotlib canvas.

figure = Figure(figsize=(5, 4), dpi=100) plot = figure.add_subplot(1, 1, 1) 

There are some options which can be configured here, such as figsize which takes a width by height in inches, and the dpi. We can specify the position of the subplot, here we use (1, 1, 1) as the top-left corner, which will cause the subplot to take up the entire figure.

This doesn’t draw anything to screen yet, in order to do that we need to create an instance of FigureCanvasTkAgg . To the best of my knowledge we will need to do this every time we finish updating the canvas.

canvas = FigureCanvasTkAgg(figure, root) canvas.get_tk_widget().grid(row=0, column=0) 

Then of course to begin the application

The code up to this point will draw a blank graph, like this:

Blank graph

Now we can start plotting points on our graph. To do so, we use the plot method on the subplot we created earlier

plot.plot(0.5, 0.3, color="#C41E3A", marker="o", linestyle="") 

This will plot a single point at coordinates (0.5, 0.3) . We can also plot multiple points at once by passing separate lists of x and y values.

x = [ 0.1, 0.2, 0.3 ] y = [ -0.1, -0.2, -0.3 ] plot.plot(x, y, color="blue", marker="x", linestyle="") 

This will plot the points (0.1, -0.1) , (0.2, -0.2) , and (0.3, -0.3) . For colors, matplotlib features a few built in colors which can be seen here, or you can specify then as a hex triplet. There are many different marker styles to choose from, here is a full list. Finally, by default, matplotlib will connect all points we plot, but we can turn this off by passing an empty linestyle .

Here we drew our points all at once, but if we had drawn them dynamically (e.g. as a result of pressing a button) we would have needed to create the FigureCanvasTkAgg object again and regrid it, as demonstrated above.

So the final code for our graph application:

from tkinter import * from tkinter.ttk import * import matplotlib matplotlib.use("TkAgg") from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg root = Tk() figure = Figure(figsize=(5, 4), dpi=100) plot = figure.add_subplot(1, 1, 1) plot.plot(0.5, 0.3, color="red", marker="o", linestyle="") x = [ 0.1, 0.2, 0.3 ] y = [ -0.1, -0.2, -0.3 ] plot.plot(x, y, color="blue", marker="x", linestyle="") canvas = FigureCanvasTkAgg(figure, root) canvas.get_tk_widget().grid(row=0, column=0) root.mainloop() 

Final graph

So that is a quick, simple, and customizable way of visualizing data.

Источник

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