0% found this document useful (0 votes)
1 views22 pages

Mapping Data

The document outlines a project to create an interactive map using Python, where users can learn facts about the world based on selected datasets. It details steps for loading data, creating a visual representation with pins, and making the map interactive by allowing users to click on pins to retrieve information. The project includes guidance on organizing data, defining functions, and debugging common issues encountered during development.

Uploaded by

caiosandrocel4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views22 pages

Mapping Data

The document outlines a project to create an interactive map using Python, where users can learn facts about the world based on selected datasets. It details steps for loading data, creating a visual representation with pins, and making the map interactive by allowing users to click on pins to retrieve information. The project includes guidance on organizing data, defining functions, and debugging common issues encountered during development.

Uploaded by

caiosandrocel4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Projects

Mapping data
Use Python to make an interactive map that
lets users learn interesting facts about the world

Step 1 You will make

Use Python to make an interactive map that lets users learn interesting facts about the world.

You will:

Use lists and dictionaries to store data


Use functions and parameters to keep your code clean
Use code to quickly explore large amounts of data

Get ideas 💭
You are going to make some design decisions about what data you want to show to your users, as well as
what style of map and pins you will use to display that data.
You can find the World happiness measures project here [Link]
happiness-measures

You can find the Ink world happiness project here [Link]
happiness

You can find the World carbon data project here [Link]
data

You can find the GDP project here [Link]


Step 2 Choose and load a data set

Do you have an idea of the kind of display you want to create? Use this step to choose your data and
load it into dictionaries. Later, you’ll use those dictionaries to build your map.

Open the Mapping Data starter project ([Link]


ta-starter) project. The code editor will open in another browser tab.

If you have a Raspberry Pi account, you can click on the Save button to save a copy to your
Projects.
Before you can put your data on a map, you’ll need to choose some data to display.

Choose: There are a few CSV files included in the starter project. Read their descriptions below.
Then note the name of the file you’d like to use in your display.

CSV files are Comma-Separated Values files. They contain data in rows and columns, like
a table. Each line is a row, with commas separating that row’s values into columns.

Olympic host nations

World population

Carbon emissions

Threatened species

National wealth

World happiness

Now that you have picked your data, you need to load it into your program.

Define a load_data() function to take a file_name variable. Have your function open that file and
print() out every line in it.

Parameters in functions

[Link] — load_data()
13 # Put code to run when the mouse is pressed here
14 def mouse_pressed():
15 pixel_colour = Color(get(mouse_x, mouse_y)).hex
16
17 def load_data(file_name):
18 with open(file_name) as f:
19 for line in f:
20 print(line)

Tip: You will be moving data around a lot in the next few steps. It’s a good idea to print()
everything out. This will help you understand what your data looks like at each step. It’s also
good for catching bugs. You can comment the print() lines out later (with #).

Add a call to load_data() in your setup() function, you can delete the pass that is already in
there. Pass it the name of the data file you chose above. You can check the list below if you
need a reminder of the file name.

Olympic host nations — [Link]


World population — [Link]
Carbon emissions — [Link]
Threatened species — [Link]
National wealth — [Link]
World happiness — [Link]

Test: Run your program. Check the data that prints out in the output area.

Debug: You might get an error message about your file name being ‘not defined’. If you do,
check that you have put the name in quotes when you call the load_data() function. For
example, load_data('[Link]').

Now the data is loaded, you need to get the data for each region and break it into a list. Then you can load
that list into a dictionary.
Add code to your load_data() function to use the split() function to break each line into a list.
Call that list info.

Split a text string into a list

[Link] — load_data()

def load_data(file_name):
with open(file_name) as f:
for line in f:
#print(line)
info = [Link](',')

Now use the list you made from each region’s data to create a dictionary for each region. Include the
name of the region and the numbers you want to use in your display.

Add code to your load_data() function that converts the data you’ve chosen into a dictionary.

Use print() to check the dictionaries look like you expect.

Field names for the csv files

[Link] — load_data()

def load_data(file_name):
with open(file_name) as f:
for line in f:
#print(line)
info = [Link](',')
# Change the dictionary to match the data you're
using
region_dict = {
'region': info[0],
'happiness rank': info[1],
'happiness score': info[2]
}
print(region_dict)
Test: Run your code and check that the dictionaries it prints out look like you expect them to: a
‘name’ key with a text string for a value, and whatever keys and values you expect based on
your code.

Debug: If you see a message about list index out of range, check that you are trying to load
the right number of values into your region dictionary. This may be a different number of values
to the example code above. You should also use key names that match the data you chose.

Now your load_data() function creates dictionaries for each region. You need to store those dictionaries
somewhere the rest of your program can get them. A list is a good choice.

Create an empty list called region_list.

[Link]

#!/bin/python3
from p5 import *
from regions import get_region_coords

region_list = []

In load_data(), add each of your dictionaries to region_list using append. This will let you work
with the data in the rest of your program.

[Link] - load_data()

def load_data(file_name):
with open(file_name) as f:
for line in f:
info = [Link](',')
region_dict = {
'region': info[0],
'happiness rank': info[1],
'happiness score': info[2]
}
#print(region_dict)
region_list.append(region_dict)

Add a line in your setup() function that prints the region_list out.
Test: Run your program and check that it prints out a list of dictionaries. It should look
something like this:

Tip: Like the other print() statements you’ve used, you can comment this line out once you’ve
used it for testing and your code works as expected.

Debug: You might find some bugs in your project that you need to fix. Here are some common
bugs.

My code doesn't run

I get a message that the csv file is 'not defined'

My info list just has one big item in it

I get a message that split is 'not defined'

I get a message that region_list is 'not defined'

Save your project


Step 3 Pick a map and pins

Choose how you’ll display the data you’ve selected.

Add code to your setup() function to set the size of your canvas to 991 pixels wide and 768
pixels high.

[Link] - setup()

# Put code to run once here


def setup():
size(991, 768)
load_data('[Link]')

Think about how you want to display the data you’ve picked: what kind of map do you want to
use?

[Link]
[Link]
mercator_bw.png
[Link]
[Link]
Choose: The starter project includes five map images. Pick one you like, and load the image in
a preload function.

[Link]

def preload():
global map
map = load_image('[Link]')

Add code to your setup() function to draw the map so it covers the whole canvas.

Coordinates in p5

[Link] - setup()

def setup():
# Put code to run once here
size(991, 768)
load_data('[Link]')
image(
map, # The image to draw
0, # The x of the top-left corner
0, # The y of the top-left corner
width, # The width of the image
height # The height of the image
)

Test: Run your program and look at your map!


Choose: What shape of pin will you place in each location? Your pin will need to be a single
colour so that it is easy for a user to click on.

You could choose a single shape, such as:

A circle
A square
A triangle

Or you could create a pin out of multiple geometric shapes, such as:

A heart
A map pin
A star
Define a function called draw_pin. It should draw a pin, of your own design, on the map. It
should take three parameters:

The x coordinate for the pin.


The y coordinate for the pin.
The colour of the pin. This should be a p5 Color().

[Link] - draw_pin()

def draw_pin(x, y, colour):


# Put code to draw your pin here

As you create your draw_pin function, call it to see how it appears on the screen. You should call
your draw_pin function from the setup() function.

You can use the arguments shown below to place a red pin the middle of the screen.

[Link] - setup()

def setup():
# Put code to run once here
size(991, 768)
image(
map, # The image to draw
0, # The x of the top-left corner
0, # The y of the top-left corner
width, # The width of the image
height # The height of the image
)
draw_pin(300, 300, Color(255,0,0))
Parameters in functions

Colours in p5

RGB colours

Draw an ellipse

Draw a rectangle

Draw a triangle

Tip: Your draw_pin function can make other shapes out of these basic ones.

Debug: You might find some bugs in your project that you need to fix. Here are some common
bugs.

My map isn't loading

My map is the wrong size

My pin isn't appearing

Save your project


Step 4 Mark your data

Display your data on the map, and make it interactive.

Before you can put pins on the map for each place you have data about, you need to know where those
places are. The starter project includes code to give you those locations.

You can use get_region_coords() to return a dictionary of the coordinates for a region. For example
get_region_coords('Japan') will return {'x': 880.151122422, 'y': 278.639809465}.

Define a draw_data() function to put your data on the map. At first you can just print out the
region’s name and its x and y coordinates.

It should loop through your region_list and print a line for each region.

[Link] — draw_data()

def draw_data():
for region in region_list:
region_name = region['name'] # Get the name of the region
region_coords = get_region_coords(region_name) # Use the
name to get coordinates
region_x = region_coords['x'] # Get the x coordinate
region_y = region_coords['y'] # Get the y coordinate
print(region_name, region_x, region_y)
In your setup() function, comment out your draw_pin() code and instead call draw_data().

[Link] - setup()

def setup():
# Put code to run once here
size(991, 768)
image(
map, # The image to draw
0, # The x of the top-left corner
0, # The y of the top-left corner
width, # The width of the image
height # The height of the image
)
# draw_pin(300, 300, Color(255,0,0))
draw_data()

Instead of printing out the name of the region, and its coordinates, you can use your draw_pin()
function to place your pins on the map. The code below colours the pins red (Color(255, 0, 9)),
but you can choose a different colour.

[Link] — draw_data()

def draw_data():
for region in region_list:
region_name = region['name'] # Get the name of the
region
region_coords = get_region_coords(region_name) # Use
the name to get coordinates
region_x = region_coords['x'] # Get the x coordinate
region_y = region_coords['y'] # Get the y coordinate
#print(region_name, region_x, region_y)
region_colour = Color(255, 0, 0) # Set the pin colour
draw_pin(region_x, region_y, region_colour) # Draw the
pin
Test: Run your program. You should see lots of pins pop up on your map! Depending on the
data you chose, you might see more or fewer pins than in the image below.

Next, you need to add some code to let users click on a pin and see some information printed out. To do
this, each pin needs to be a different colour, and you need a way to match those colours to the right data.

Choose: Every pin needs a unique colour. But there are lots of different ways to make this
happen. Here are a few suggestions, but you can create your own.

Change the value of one colour

Change the value of multiple colours

Choose random colours

Test: Run your program and check that the pins are different colours. If you don’t have many
pins, it may be hard to tell. In that case, try using bigger changes between each pin.

Your map has unique pins for each location, but you need to add some code to connect those pins to the
information you want to show your users.
To use the pin’s colour to look up the information, you need to create a dictionary to store the
colours and link them to the region.

[Link]

#!/bin/python3
from p5 import *
from regions import get_region_coords
from random import randint

region_list = []
colours = {}

As the pins are placed, the region can be stored in the dictionary along with the colour of the
pin.

[Link]

def draw_data():
red_value = 255
for region in region_list:
region_name = region['name'] # Get the name of the
region
region_coords = get_region_coords(region_name) # Use
the name to get coordinates
region_x = region_coords['x'] # Get the x coordinate
region_y = region_coords['y'] # Get the y coordinate
region_colour = Color(red_value, 100, 0) # Set the pin
colour
colours[region_colour.hex] = region
draw_pin(region_x, region_y, region_colour)
red_value -= 1

When the user clicks on a pin, the hex colour value of the pin is retrieved, and then the corresponding
region is found in the dictionary.
In your mouse_pressed() function, lookup the pixel_colour in the colours dictionary and print out
the region.

Remember that colours is a dictionary of dictionaries. You will have to get the dictionary of
region information, then get the information from inside that dictionary. For example:

[Link]

def mouse_pressed():
# Put code to run when the mouse is pressed here
pixel_colour = Color(get(mouse_x, mouse_y)).hex
facts = colours[pixel_colour]
print(facts['region'])

It’s important to check if a key is in a dictionary. If you click on an area of the map without a
pin, you will receive a KeyError.

You can check if a value is in a dictionary by using in:

[Link]

def mouse_pressed():
# Put code to run when the mouse is pressed here
pixel_colour = Color(get(mouse_x, mouse_y)).hex
if pixel_colour in colours:
facts = colours[pixel_colour]
print(facts['region'])
else:
print('Region not detected')

Test: Run your program. Click on a pin and check that your program correctly prints out data
about that area.
You can print out other facts about the region you clicked on by adding more print()
statements. This will depend on the data set that you used. If you used [Link] for instance,
you could print the following:

[Link]

def mouse_pressed():
# Put code to run when the mouse is pressed here
pixel_colour = Color(get(mouse_x, mouse_y)).hex
if pixel_colour in colours:
facts = colours[pixel_colour]
print(facts['name'])
print(facts['happiness_rank']) # Your first data fact
print(facts['happiness_score']) # Your second data
fact
else:
print('Region not detected')
s

Debug: You might find some bugs in your project that you need to fix. Here are some common
bugs.

My pins do not appear on the map

I get a message about a 'KeyError'

It keeps displaying 'Region not detected'

Save your project


Upgrade your project
If you have time you can upgrade your project.

Here are some ideas you could try:

Use pins to display data — change the size or shape of the pin based on some value in the region’s
data. You can combine changes in shape and size to show even more.
Filter the data — use if statements to only show pins on the map that meet conditions you choose. For
example, only showing places where less than half the people live in cities. For an extra upgrade, let
the user choose which filters to use.
Add a second data file — create another file of data and display it using different pins. Can you use
some of your existing functions if you make some small changes? Do you want to use two sets of pins,
or put all the data together on one pin?

Multicoloured pins: Population density

This project uses small multicoloured square pins and uses the population data set.

You can find the Population density project here ([Link]


-population).

Data-sized pins: Olympic host countries

This project has been upgraded to show larger pins for areas that have hosted the Olympic Games more
often.

You can find the Olympic host countries project here ([Link]
data-olympics).

Filter data: Global population — rural and urban

This project has been upgraded to allow you to choose the data used to make the display.

You can find the Global population — rural and urban project here ([Link]
cts/urban-rural-population).

Save your project


Share
If you are in a club, why not share your project with friends?

Inspire the Raspberry Pi Foundation community with your project!

To submit your project to our ‘Mapping data - Community’ ([Link] studio,


please complete this form ([Link]

Published by Raspberry Pi Foundation ([Link] under a Creative Commons


license ([Link]
View project & license on GitHub ([Link]

Published by Raspberry Pi Foundation ([Link] under a Creative


Commons license ([Link]
View project & license on GitHub ([Link]
data)

Accessibility ([Link]
Cookies Policy ([Link]
Privacy Policy ([Link]
Translate for us (/en/projects/translating-for-raspberry-pi)

You might also like