How to Create Simple Visualizations with Google Charts and Pandas Dataframes | by Alan Jones | Towards Data Science

Google Charts have been around for more years than I care to remember, so I think we can safely assume that it is a mature and stable technology.
It can also be used to create attractive charts and graphs.
Here, we can see a simple line chart which is interactive to the extent that when you hover over a point on the graph it will show you the detail of that data point.
We are going to look at how to create charts like this using some elementary boilerplate code in HTML and Javascript, Pandas dataframes, and a simple Flask web application. We’ll develop the complete code, below. (At the end of this article I’ll include a link to an app where you can see the code in action and download the code and sample data.)
Here’s an outline of what follows:
writing a basic Flask app (optional)
displaying a chart using boilerplate HTML and Javascript
creating a Pandas dataframe and converting it to a form compatible with Google Charts
Putting the Flask code and the web page together as an app
This is a very brief introduction to creating and running a Flask app. If you already know how to do this then you can safely skip this section.
Flask is a web application micro-framework which means it is a very lightweight library for developing web apps. Creating your first Flask app is easy but first you will need to install it with pip or conda, for example:
pip3 install flask
Next, open a new directory and create a file app.py with the following code:
from flask import Flaskapp = Flask(__name__)@app.route('/')def root():   return 'Hello'
The code is pretty straightforward. The first line imports the Flask library; the second creates a Flask object (that will be run); and the rest of it defines a route. A route is a web page, or endpoint, and the @app.route decorator defines the url, in this case it is the root url (i.e. /). Below this is a function definition that tells the Flask server what to do when this particular endpoint is requested — in this case simply return the string “Hello”.
Now open a terminal window, navigate to the correct directory, and type:
python3 -m flask run
(Note: I’m using Python3 in a standard Linux environment, here, if you are using a different environment where Python3 is the default — portable Python or Conda, for example — then your command may be python not python3.)
This will start the Flask server and the result should be this:
Flask is now running your app and it is available at the url, http://127.0.0.1:5000, so type that into the address bar in a browser and you should see something like this:
We are going to be using templates later to connect the Flask app to a web page but, for now, that’s all we need to know about Flask.
Now we’ll take a look at a template HTML page that can be reused for many different applications. The basic file layout looks like this:
<!DOCTYPE html><html>  <head>    <script>      // Script 1 — where the data gets loaded    </script>    <! — Script 2 — Load the AJAX API →    <script src=”https://www.gstatic.com/charts/loader.js">       </script>    <script>      // Script 3 — Where we create and display a chart    </script>  </head>  <body>    <! — the div where a chart will be displayed →    <div style=”width:600px; height:300px” id=”chart1"></div>  </body></html>
This is a simple HTML file with a single <div> in the body and 3 scripts in the head.
The <div> is where the chart will be displayed and is given an id — I’ve also given it a height and width. The id is compulsory, the sizing is not — you can mess around with the height and width or leave them out completely as you wish.
The main logic comes in the three scripts. The first one, Script 1, will be where we load the data. For this first example I’ll create the data locally but later we’ll load it from a Pandas dataframe. The second script, Script 2, loads a Google Charts API which will be used by Script 3. And Script 3. itself, does the main work of creating and displaying the chart.
We’ll see how these work in a second but it is worth pointing out that if you want to create your own app, you will only need to change Script 1 and the HTML. So very little Javascript programming is required.
Script 2 is already defined and we don’t need to modify it.
Script 3 is rather longer but, again, once we have defined it we don’t need to change it. Here it is:
<script>  // Load the Visualization API and the corechart package  google.charts.load(‘current’, {‘packages’:[‘corechart’]});  // Set a callback for when the API is loaded  google.charts.setOnLoadCallback(drawChart);    // This is the callback function which actually draws the chart  function drawChart(){    google.visualization.drawChart({      "containerId": containerId,      "dataTable": data,      "chartType": chartType,      "options": options    });  }</script>
What’s happening here is that we are loading the visualization API from Google and then setting a callback function that will be run when the API has finished loading. The call back function is drawChart and does exactly what it says.
drawChart simply calls another function, by the same name, from the Google API and passes a number of parameters that we will define later in Script 1. Let’s go through those parameters.
containerId is the id of the <div> where the chart will be displayed.
data is the actual data to be plotted.
chartType is the type of plot that we want, for example, LineChart, PieChart, ColumnChart.
options can include a number of different options for the chart, for example a title.
We will define these options in Script 1.
In order to get a working web page, first we’ll define the data locally — we’ll import it from a python app later.
You can define the data for Google Charts in a few different ways but the simplest, for our purposes, is a simple table. Here’s a table of the number and make of cars parked in my street:
But we need to format it as a list of rows in a Javascript two-dimensional array. This is pretty much the same as a Python list of lists. It looks like:
[  ["Car","Number"],  ["Audi", 3],  ["BMW", 2],  ["Mercedes", 1],  ["Opel", 3],  ["Volkswagen", 4]]
The first item in the list is a list of column names and the rest are the rows of data.
Here is a Script 1, that incorporates that data and the options that we saw earlier..
<script>  data = [    ["Car","Number"],    ["Audi", 3],    ["BMW", 2],    ["Mercedes", 1],    ["Opel", 3],    ["Volkswagen", 4]  ];  chartType = "ColumnChart";  containerId = "chart1";  options = {"title":"Cars parked in my road"};</script>
The first thing we see is a variable data that contains the car table. Next is the type of chart that we are going to plot and then the id of the <div> that the chart will be drawn in. Finally, we set the options for the chart — here this is just the title but there could be other options depending on the type of chart we want to plot. You will see how the options are used later.
If you put these scripts together with the HTML template above, you will have a working web page. You can open it in your browser and see the resulting graph.
Now here is a neat trick: change the line
chartType = “ColumnChart”;
to
chartType = “PieChart”;
save it and reload the web page and...
That was easy!
OK, but this is just a simple stand-alone demonstration, in reality we want to get our data from elsewhere. And that is where we are going next.
We can see that the format of the data provided in the example was a list of lists. The first element of the list was a list containing the column titles and the remainder contained data that form the rows of a table.
While this is not very different in concept to a Pandas dataframe, we do need to do a little work to convert one to the other.
Let’s first of all write some Python code to load in our data and create a dataframe that represents the data that we want to plot.
If you download the program file you will find in the root directory a file called london2018.csv which we are going to load into a Pandas dataframe like this:
url = ‘london2018.csv’weather = pd.read_csv(url)
The dataframe looks like this:
It’s a record of weather statistics in London for the year 2018 (derived from the UK Met Office data). Tmax and Tmin are the maximum and minimum temperatures for each month in 2018, Rain is the total rainfall in millimetres, and Sun is the total number of hours of sunshine.
We are going to produce a temperature chart we only need Tmax and Tmin and the Month columns, so we create a new dataframe of the data that we need like this:
title = “Monthly Max and Min Temperature”temps = weather[[‘Month’,’Tmax’,’Tmin’]]temps[‘Month’] = temps[‘Month’].astype(str)
Notice that I’ve also converted the Month column to a string because it doesn’t make much sense for it to be treated as a number and I’ve also created a title for the chart.
So now we have the data we want; we just need to convert it into the shape that Google charts will deal with. We do this by extracting the values from the chart and convert them to a list. This will give us the values as a list of lists, exactly what we need for the chart. One problem: the column names are not included. That’s easily solved, we extract the column names and then append the resulting list to the top of the values list.
d = temps.values.tolist()c = temps.columns.tolist()d.insert(0,c)
Now we bundle the data and the title into a JSON string that we can pass to the web page.
tempdata = json.dumps({'title':title,'data':d})
We pass the data to the web page using a template mechanism that is built into Flask. Like this:
return render_template('weather.html', tempdata=tempdata)
The render_template function finds the template weather.html and creates a web page by inserting the data passed to it into the template.
So now we need to modify our html file to make it into a template. That means changing Script 1 into some that will load the JSON data into Javascript variables by putting named placeholders where the data being passed in will go. (A palace holder is a pair of double curly braces with a name inside.)
In our case there is only one data item called tempdata. So we replace the code in Script 1 with this:
<script>  tdata = JSON.parse({{tempdata|tojson|safe}});  tempdata = tdata.data;  temptitle = tdata.title;  chartType = "LineChart";  containerId = "chart1";  options = {"title":temptitle};</script>
The name is enclosed in double curly braces, {{name}}, and here we are also saying that the data should be converted to json and that it contains ‘safe’ HTML, that is to say, we don’t want any of the special characters converted into escape sequences.
Having got the data into the template we assign it to the variable tdata and from that set variables for the data and the title.
So we end up with two the two files that you can see in Listings 1 and 2.
Now this bit is important: first, we call the Flask app app.py, second, the Flask app expects the HTML file to be called weather.html (as we see in the listing), so make sure you give it that name. Lastly, Flask expects it’s templates to be a directory called templates which is in the same directory as the Flask app.
And when you run the flask app, you’ll get the following page.
There is a great deal more to Google Charts than this but I hope this has been a useful introduction to generating them with a Python app. Thanks for reading.
Download the zip file here and see the basic app here.
When you have downloaded the files, unzip them into an empty folder and run the Flask app with python -m flask run (as above).
I may take this code further and/or write more articles on this topic. If you would like to be kept up-to-date with new articles, please consider subscribing to my occasional free newsletter here.