Graphing with Tkinter

Tkinter is not a graphing tool. However, should you need to draw graphs with Tkinter, you can use the Canvas widget to draw graphs.

In this iteration, we will draw the following graphs:

  • Pie chart (8.02_pie_chart.py)
  • Bar graph (8.03_bar_graph.py)
  • Scatter plot (8.04_scatter_plot.py)

The three graphs show up as follows:

Let's look at the pie chart first. You can easily create a pie chart in Tkinter using the Canvas widget's create_arc method. 

The create_arc method has the following signature:

item_id = canvas.create_arc(x1, y1, x2, y2, option, ...)

Point (x1, y1) is the top-left corner and point (x2, y2) is the bottom-right corner of the rectangle into which the arc fits. If the bounding rectangle is a square, it makes a circle. The method also takes two arguments, named start and extent, which we will use to create the pie chart.

The start option specifies the start angle for the arc, measured in degrees from the +x direction. When omitted, you get the complete ellipse. The extent option specifies the width of the arc in degrees.

The arc begins at the angle given by the start option and draws counterclockwise up to the degrees specified by the extent option.

To create the pie chart, let's define a method that, given a number n, divides the circle into, say, 1,000 equal parts and then, given a number less than 1,000, returns the equivalent angle in the arc. Since there are 360 degrees in a circle, the method is defined as follows:

total_value_to_represent_by_pie_chart = 1000
def angle(n):
return 360.0 * n / total_value_to_represent_by_pie_chart

Next, we plot the various sections of the pie chart using code like this:

canvas.create_arc((2,2,152,152), fill="#FAF402", outline="#FAF402", start=angle(0), extent = angle(200))

You can check out an example of a pie chart in 8.02_pie_chart.py.

Next, the bar graph. This is very simple. We use create_rectangle to draw a bar graph:

plot_data= [random.randint(75,200) for r in range(12)]
for x, y in enumerate(plot_data):
x1 = x + x * bar_width
y1 = canvas_height - y
x2 = x + x * bar_width + bar_width
y2 = canvas_height
canv.create_rectangle(x1, y1, x2, y2, fill="blue")
canv.create_text(x1+3, y1, font=("", 6),
text=str(y),anchor='sw' )

One important thing to note here. Since the Canvas widget represents the y coordinate starting from the top-left corner, we need to subtract the y position from the canvas height to get the y coordinate for the graphs.

You can check out the complete code of the bar graph in 8.03_bar_graph.py.

Similarly, we use the create_oval method to draw the scatter plot. Check out the code for the scatter plot in 8.04_scatter_plot.py. 

Next, let us see how to embed matplotlib graphs in Tkinter.

Using the Tkinter canvas to draw graphs may work fine for trivial cases. However, Tkinter is not the best choice when it comes to drawing more sophisticated and interactive graphs.

Several Python modules have been developed for making graphs. However, matplotlib stands out as a clear winner for producing professional-quality interactive graphs with Python.

Although a detailed discussion on matplotlib is beyond the scope of this book, we will take a brief look at embedding matplotlib-generated graphs on a Tkinter canvas.

You can install matplotlib and NumPy (a dependency for matplotlib) using the following commands:

pip3 install matplotlib
pip3 install numpy

The matplotlib targets many types of use cases and output formats. Some of the different use cases for matplotlib are to:

  • Make interactive graphs from the Python shell
  • Embed matplotlib in GUI modules such as Tkinter, wxPython, or PyGTK
  • Generate postscript images from simulations
  • Serve on web pages from backend web servers

In order to target all these use cases, matplotlib uses the concept of a backend. In order to display a matplotlib graph on Tkinter, we use a backend called TkAgg.

We import the backend into matplotlib as follows:

import tkinter as tk
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAgg
from matplotlib.figure import Figure

We then create the matplotlib graph as we would normally do in the matplotlib API:

f = Figure(figsize=(5,4), dpi=100)
a = f.add_subplot(111)
t = arange(-1.0, 1.0, 0.001)
s = t*sin(1/t)
a.plot(t, s)

Finally, we embed the generated graph in the tkinter main loop using the TkAgg backend as follows:

canvas = FigureCanvasTkAgg(f, master=root)
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

We can also embed the navigation toolbar of matplotlib using the command:

toolbar = NavigationToolbar2TkAgg(canvas, root )
toolbar.update()

The preceding code (8.05_matplotlib_embedding_graphs.py) generates a graph as shown in the following diagram:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.60.63