Plotting on the web (with Javascript D3)

We have seen how to plot a bar chart with Python, now let’s see how it can be done for the web so that it can be displayed in any (recent) browser as it is the quickest way to reach a global audience (regardless of the operating system and device type.

We will use the same data and chart as in the Python example.

To plot it, I will use the D3 library, probably the most used javascript library for web visualisation.
This small tutorial assumes that you know Javascript and the W3C DOM.
Continue reading “Plotting on the web (with Javascript D3)”

Plotting in Python – introduction

It is often said that a picture is worth thousands of words. This is especially true when coming to data: charts make the data properties immediately apparent.

Let’s start with a simple chart: a bar graph is a chart with rectangular bars whose lengths are proportional to the values that they represent. They are often used to compare data that fits into categories (histograms – sometimes confused with bars – are used for continuous data).

I will use as example the World Heritage sites, specifically the list of the top 10 countries with the highest number of sites.
The list is short (as a matter of fact 10 items) and can be represented in Python by a dictionary, better known as associative array (basically a collection of unique key + value pairs):

whcTop10 = {'Italy': 50, 'China': 47, 'Spain': 44, 'Germany': 39, 
            'France': 39, 'Mexico': 32, 'India': 32, 'UK': 28, 
            'Russia': 26, 'USA': 22}

As you see the key is a string (the name of the country) and the value is the number of sites in that country.
The Python dictionaries are orderless (if you print it, the order of the items will be different) so the items (lands on X axis and sites on Y axis) need first to be sorted, to have a better chart.
Note: there is a library available called Collections that have Ordered Dictionary as data structure, that can be used too. For this simple example would be though overkilling.

                   # the frequency for y axis, from highest to lowest
nSites = sorted(whcTop10.values(), reverse = True) 
                   # the list of all top 10 lands, sorted by sites                      
lands = sorted(whcTop10.keys(), key=whcTop10.__getitem__, reverse=True)

To plot the chart, I will use the pyPlot module, part of the MatPlotLib library (which is included in many Python installations):

import matplotlib.pyplot as pypl   # pypl: you can put any other name...
landAsX = range (10)          # the x locations for the groups
""" plot the bar chart """ (landAsX, nSites)    # format data as bar chart                  # display it

This is the chart produced with just a few lines of codes:

Step 1. simple chart
Step 1. simple chart

Continue reading “Plotting in Python – introduction”