Adventures in Machine Learning

Creating Stunning Data Visualizations with Matplotlib and Tkinter GUI

Creating data visualizations is an essential aspect of data analytics and reporting. It tells a story about the data, making it easy to understand and gain insights from.

Python offers several libraries to create charts, and one of the most popular is Matplotlib. However, Matplotlib charts can be a bit challenging to embed on a GUI.

In this article, we will explore how to embed Matplotlib charts on a Tkinter GUI step by step.

Preparing Datasets

Before we create our data visualization, we need to prepare the datasets. In this tutorial, we will use a bar chart, line chart, and scatter diagram to display different kinds of data.

Therefore, we need relevant data for each chart. For our bar chart, we will create a dataset of the best-selling cars in 2021.

1. Best-Selling Cars Dataset

Brand Number of Sales
Toyota 538,355
Ford 401,566
Chevrolet 332,981
Honda 324,901
Nissan 247,257

For the line chart, we will create a dataset to show the average temperature of a city over time. We will use the following data:

2. Average Temperature Dataset

Date Temperature (C)
Jan 1, 2021 15
Feb 1, 2021 12
Mar 1, 2021 20
Apr 1, 2021 25
May 1, 2021 28
Jun 1, 2021 32

For the scatter diagram, we will create a dataset to show the correlation between car prices and ratings.

3. Car Prices and Ratings Dataset

Car Price ($) Rating
Toyota Camry 24,970 8.1
Ford Fusion 23,170 8.0
Honda Accord 23,800 8.3
Nissan Altima 24,100 7.8
Chevrolet Malibu 22,140 7.6

Creating DataFrames in Python

Before we plot our charts, we need to import these datasets into pandas dataframes. We can use the following code to create the dataframes:

import pandas as pd

# Creating the dataframe for the bar chart
df_bar = pd.DataFrame({
    'Brand': ['Toyota', 'Ford', 'Chevrolet', 'Honda', 'Nissan'],
    'Number of Sales': [538355, 401566, 332981, 324901, 247257]
})

# Creating the dataframe for the line chart
df_line = pd.DataFrame({
    'Date': ['Jan 1, 2021', 'Feb 1, 2021', 'Mar 1, 2021', 'Apr 1, 2021', 'May 1, 2021', 'Jun 1, 2021'],
    'Temperature (C)': [15, 12, 20, 25, 28, 32]
})

# Creating the dataframe for the scatter diagram
df_scatter = pd.DataFrame({
    'Car': ['Toyota Camry', 'Ford Fusion', 'Honda Accord', 'Nissan Altima', 'Chevrolet Malibu'],
    'Price ($)': [24970, 23170, 23800, 24100, 22140],
    'Rating': [8.1, 8.0, 8.3, 7.8, 7.6]
})

Creating the GUI

Now that we have our datasets ready, we can proceed to create the GUI. We will use Tkinter to create a simple interface where we will display the charts.

import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk

# Creating the GUI
root = tk.Tk()
root.title('My Data Visualizations')
root.geometry('800x600')

# Creating the figure and adding subplots
fig = plt.figure(figsize=(10, 10))
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)

# Adding the subplots to the canvas
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

We start by importing the necessary libraries, including Tkinter, Matplotlib, and FigureCanvasTkAgg. We then create the root window, set its size, and give it a title.

We then create the figure and add three subplots to it. Finally, we create the canvas and add the subplots to it.

Creating Bar Chart

Now that we have the GUI set up, we can start plotting the charts. We will first create a bar chart using the best-selling cars dataset.

1. Bar Chart Code

# Plotting the bar chart
df_bar.plot(kind='bar', x='Brand', y='Number of Sales', legend=False, ax=ax1)
ax1.set_title('Best-selling Cars in 2021')

We use the plot() function to plot the bar chart. We specify the kind of chart (in this case, a bar chart), the x-axis (Brand), the y-axis (Number of Sales), and turn off the legend.

We also set the title of the plot using the set_title() method.

Creating Line Chart

Next, we will create a line chart using the temperature dataset. We can use the following code:

2. Line Chart Code

# Plotting the line chart
df_line.plot(kind='line', x='Date', y='Temperature (C)', color='r', marker='o', fontsize='10', legend=False, ax=ax2)
ax2.set_title('Average Temperature of a City Over Time')

We use the plot() function again to plot the line chart.

We specify the kind of chart (a line chart), the x-axis (Date), the y-axis (Temperature), and set the line color and marker. We also set the font size, turn off the legend, and set the chart title using the set_title() method.

Creating Scatter Diagram

Finally, we will create a scatter diagram using the car prices and ratings dataset. We can use the following code:

3. Scatter Diagram Code

# Plotting the scatter diagram
df_scatter.plot(kind='scatter', x='Price ($)', y='Rating', legend=False, ax=ax3)
ax3.set_title('Car Prices and Ratings')

We use the plot() function again to plot the scatter diagram.

We specify the kind of chart (a scatter diagram), the x-axis (Price), and the y-axis (Rating). We also turn off the legend and set the chart title using the set_title() method.

Conclusion

In this tutorial, we learned how to embed Matplotlib charts on a Tkinter GUI. We started by preparing the datasets by importing them into pandas dataframes.

We then created the GUI using Tkinter and added the plots to it using the Matplotlib library. We created a bar chart, line chart, and scatter diagram to display different kinds of data.

With this knowledge, we can create stunning data visualizations that communicate complex data in a simple and understandable way. In the previous section, we explored how to embed Matplotlib charts on a Tkinter GUI.

We started by preparing datasets using different types of data, such as the best-selling cars, average temperature of a city, and car prices and ratings. We then imported the datasets into pandas dataframes and created the GUI using Tkinter.

We added subplots to the GUI and created different types of charts, including a bar chart, a line chart, and a scatter diagram. Now, we will take a deeper look at the steps involved in creating the Matplotlib charts and how to customize them to suit our needs.

Creating the GUI using Tkinter

Creating the GUI is the first step in embedding Matplotlib charts on a Tkinter GUI. To create a GUI, we start by importing the necessary libraries, including Tkinter and Matplotlib.

Next, we create a root window using Tkinter and set its size and title. Once we have the root window, we create a figure using Matplotlib and set its size using the figsize parameter.

We then add subplots to the figure using the add_subplot() method. Finally, we create a canvas using FigureCanvasTkAgg and add the subplots to it using the draw() method.

Customizing the Charts

After creating the GUI and adding subplots, we can start creating our charts. Different kinds of charts require different approaches to create them.

We can customize the charts further by changing their appearance, such as the color, style, font size, and title.

Creating a Bar Chart

To create a bar chart, we use the plot() function and set the kind parameter to ‘bar’. We specify the x-axis and y-axis data using the x and y parameters.

We can further customize the chart by setting the chart title using the set_title() method and turning off the legend using the legend parameter. To add more customization, we can set the color of the bars using the color parameter, the width of the bars using the width parameter, and the font size using the fontsize parameter.

We can also rotate the x-axis labels using the set_xticklabels() method.

Creating a Line Chart

To create a line chart, we again use the plot() function and set the kind parameter to ‘line’. We specify the x-axis and y-axis data using the x and y parameters.

We can customize the chart’s appearance by setting the line color using the color parameter and the marker style using the marker parameter. We can further customize the chart by setting the chart title using the set_title() method, turning off the legend using the legend parameter, and adjusting the font size using the fontsize parameter.

We can also set the line style using the linestyle parameter and add grid lines using the grid() method.

Creating a Scatter Diagram

To create a scatter diagram, we use the plot() function and set the kind parameter to ‘scatter’. We specify the x-axis and y-axis data using the x and y parameters.

We can customize the chart’s appearance by setting the marker color using the color parameter and the marker style using the marker parameter. We can further customize the chart by setting the chart title using the set_title() method, turning off the legend using the legend parameter, and adjusting the font size using the fontsize parameter.

We can also set the marker size using the s parameter, and add grid lines using the grid() method.

Embedding Multiple Charts on a Single Tkinter GUI

In this tutorial, we created different types of charts and added them to the Tkinter GUI separately. However, we can embed multiple charts on a single Tkinter GUI by using the same figure and different subplots.

We can use the add_subplot() method to add multiple subplots to the same figure and use the plot() function multiple times to create different charts. We can further customize the layout of the subplots using the subplots_adjust() method and set the location of each subplot using the grid_spec parameter.

Conclusion

In conclusion, embedding Matplotlib charts on a Tkinter GUI is a powerful way to communicate data analysis and reporting. In this tutorial, we explored how to create different types of charts, including a bar chart, a line chart, and a scatter diagram.

We also learned how to customize the appearance of the charts using different parameters such as color, style, font size, and title. Finally, we discussed how to embed multiple charts on a single Tkinter GUI.

With these skills, we can create interactive and engaging data visualizations that communicate complex data in a simple and understandable way. In this tutorial, we explored how to embed Matplotlib charts on a Tkinter GUI.

We began by preparing datasets, importing them into pandas dataframes, and creating the GUI using Tkinter. We then added subplots to the GUI and created different types of charts, including a bar chart, a line chart, and a scatter diagram.

Using Matplotlib, we demonstrated how to customize the appearance of the charts by changing the color, style, font size, and title. Finally, we discussed how to embed multiple charts on a single Tkinter GUI.

These skills are essential for creating interactive and engaging data visualizations that communicate complex data in a simple and understandable way. The takeaway from this tutorial is that with the right tools and techniques, it is possible to create beautiful charts that are both informative and aesthetically pleasing.

Popular Posts