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.
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):
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)
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 """
pypl.bar (landAsX, nSites) # format data as bar chart
pypl.show() # display it
This is the chart produced with just a few lines of codes: