Visualizing maps and bubbles

In this recipe, we will see how to visualize a map and place a bubble on each country, in this case some European countries. The size of each bubble will be proportional to the number of total reported crimes in that country.

Getting ready

Here we will again use the crim_gen.tsv file, which comes with this book, assuming that this file is in the same directory as the code using it.

How to do it...

For the following recipe, we will proceed as follows:

  1. Import and query the data.
  2. Define the coordinates of each country.
  3. Create an entry for each country.
  4. Define the layout for the chart.
  5. Invoke plotly.
    import plotly.plotly as py
    from plotly.graph_objs import *
    
    import pandas as pd
    crimes = pd.read_csv('crim_gen.tsv', sep=',|	', na_values=': ')
    crimes = crimes[crimes.country.isin(['IT','ES','DE','FR','NO','FI'])]
    
    total_crimes = crimes.query('iccs == "TOTAL"')[['country', '2012 ']].sort(columns='2012 ').values
    coords = {'IT': (13.007813, 42.553080), 'ES': (-3.867188, 39.909736), 'DE': (9.316406,50.736455),
              'FR': (2.636719, 46.195042), 'NO': (8.613281, 61.100789), 'FI': (25.839844, 62.431074)}
    scale = 300000
    countries = []
    
    
    for info in total_crimes:
        c = coords[info[0]]
        country = dict(
            type = 'scattergeo',
            lon = [c[0]],
            lat = [c[1]],
            text = info[0]+':'+str(info[1]),
            sizemode = 'diameter',
            name= info[0],
            marker = dict( 
                size = info[1] / scale, 
                color = 'red',
                line = dict(width = 1,color = 'red')
            ))
        countries.append(country)
    
    layout = dict(
            title = '2012 Reported crimes',
            showlegend = True,
            geo = dict(
                scope='europe'      
            ),  
        )
        
    fig = dict( data=countries, layout=layout )
    url = py.plot( fig, validate=False, filename='bubble-map-crimes' )

How it works...

Here, we have isolated the data for six countries: Spain, Italy, Germany, France, Norway, and Finland. For each of these countries, we defined the coordinate to place the bubble in the dictionary coords. Then, for each country, we created a dictionary with the details of the bubble to show the size, string in the tooltip, color, and geographical coordinates.

Then, we created the layout for the chart. What tells Plot.ly that this chart contains a map is the parameter geo. When Plot.ly finds this parameter in the specifications of the layout, it automatically assumes that it is a map. With this parameter, we specify the scope of the map, which in this case is Europe.

The resulting figure should be as follows:

How it works...
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.188.121