Using Widgets to Make Plotting Using Matplotlib Easy (Using Football Data)

Making plots using Matplotlib can be tough. Especially when you deal with a lot of data and lots of aspects in the plot, such as the title, the labels, annotations, different background and scatter point colours. A change in one aspect could see you searching through 100s of lines of code to find the required line, especially when you don’t use comments in your code(which is a bad practice by the way). A way to make this job easier is creating a function for your entire MPL(Matplotlib) plot and assigning parameters for various aspects of the plot. However, I thought we could make this more interactive and non-coder friendly by defining these parameters using Python widgets, which will help us select our variable cleanly and appealingly.

WHAT DATA FRAME AM I USING?

For this example, I’ll be using data from Fbref.com, an open-source football data website containing StatBomb data. I’ll be using their data for shooting in the big 5 leagues.

WIDGETS IN PYTHON

We could use Tkinter for these widgets, which is a Python binding to the Tk GUI toolkit. However, I’m not very well versed with it.

So I’ll be using ipywidgets, also known as Jupyter-widgets or simply widgets, and are interactive HTML widgets for Jupyter notebooks and the IPython kernel.

STEPS TO FOLLOW

  1. Our first step is to import all the necessary libraries we will be needing for the code.
# IMPORTING THE NECESSARY LIBRARIESimport matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib as mpl
from ipywidgets import widgets

2. Now we import the data frame. We do this using the inbuilt pandas CSV reader.

Make sure that the CSV or whatever file is in the same directory as your code.

# IMPORTING THE DATAFRAMEdf = pd.read_csv('shooting.csv',index_col='Rk')
df.head()

We see our data frame looks like this. You could alternatively web scrape this data frame, save it as an Excel or as a parquet.

DataFrame

3. I prefer to customise some default parameters of Matplotlib using rcParams. This step is optional but it’d make the plot look appealing.

# CHANGING DEFAULT PARAMETERS OF MATPLOTLIBmpl.rcParams['font.family']= 'Candara'
mpl.rcParams['font.size'] = 12
mpl.rcParams['font.weight'] = 'bold'
mpl.rcParams['legend.title_fontsize'] = 20
mpl.rcParams['legend.fontsize'] = 17

4. In my data frame the columns look like this

Columns in the data frame

I don’t need most of these columns for use later onwards, so I’ll create a variable to store only those columns I need. I’ll use index slicing for this, keep in mind your indexes may change based on the data frame you use.

# GRABBING THE COLUMNS I'LL NEED FOR LATERcolumns = df.columns.to_list()
columns = columns[8:-1]

5. COMING TO THE WIDGETS

IPyWidgets is a very fun tool to use and the link to its documentation is here. It has many cool widgets to try from and we’ll be using some of them here.

We will first create widgets for selecting the parameter for the x-axis, y-axis and whether we want to change those values to a per 90 value

Code for the Widgets

Not going into each widget's detail, we see we have text widgets, slider widgets, checkboxes, search boxes, colour choosing widgets, and dropdown widgets.

The basics you need to know are as follows. The widget's description describes what the widget is used for. The widget's value is the default value set to it. The placeholder is the text that appears in the widget until you write down the text yourself The options give the options among which different values can be chosen. For the FloatSlider widget, you also have a min and max value and a step value you need to assign it.

To call the value of the widget that you have chosen, you simply need to use the .value method after the name you have given the particular widget.

6. CREATING THE FUNCTION FOR PLOTTING

Now we create a function which when called will plot for us. We will use the values of all the widgets as parameters in the function, but that is for a later stage, let us first write the function down.

Function for plotting using MPL

I realized there was no need for the club widget in hindsight, but it was good exposure for you to learn how to make it.

KEEP IN MIND ALL THE ABOVE NEEDS TO BE EXECUTED ONLY IN JUPYTER NOTEBOOK FOR WHICH IPYWIDGETS IS BUILT

7. We now display all these widgets so that we can use them simultaneously. We do this by:

# DISPLAYING THE WIDGETSdisplay(x_val)
display(y_val)
display(per90)
display(games)
display(club)
display(player)
display(positions)
display(bgcolor)
display(text_col)
display(lab_col)
display(point_col)
display(title)
display(x_lab)
display(y_lab)

This results in a widget panel that looks like this

Unfilled Widget Panel

Let’s quickly fill these up to something of our liking

Keep in mind for selecting various positions in the positions widget you need to hold control as you do when you select files in file explorer.

Filled Widget Panel

So we see we have set our colours, our labels, our filters as well as the player we want to plot on.

8. Finally, we can plot this entire thing by calling the function and inputting all these widget values as parameters

plot_graph(x_val.value,y_val.value,per90.value,games.value,player.va   lue,positions.value,title.value,x_lab.value,y_lab.value,bgcolor.value,point_col.value,lab_col.value)

We eventually get this graph

A clean and appealing graph

Therefore by tinkering a bit with our widgets, we can alter our graph to whatever we want.

This was a very basic tutorial of what we could do with widgets in Python, of course, there is much more customizability in this, but this is a basic overview of how you can integrate two very different libraries for a single purpose.

GITHUB REPO: All code for the above will be found in this GitHub Repository along with the CSV file I used -https://github.com/shreyas7kha/MPL_Widgets

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store