Map Trove newspaper results by state¶
Version 2 of the Trove API adds the state
facet to the newspapers
zone. This means we can easily get the number of articles from a search query published in each state.
If you haven't used one of these notebooks before, they're basically web pages in which you can write, edit, and run live code. They're meant to encourage experimentation, so don't feel nervous. Just try running a few cells and see what happens!.
Some tips:
- Code cells have boxes around them.
- To run a code cell click on the cell and then hit Shift+Enter. The Shift+Enter combo will also move you to the next cell, so it's a quick way to work through the notebook.
- While a cell is running a * appears in the square brackets next to the cell. Once the cell has finished running the asterix will be replaced with a number.
- In most cases you'll want to start from the top of notebook and work your way down running each cell in turn. Later cells might depend on the results of earlier ones.
- To edit a code cell, just click on it and type stuff. Remember to run the cell once you've finished editing.
Setting things up¶
First we'll import the packages we need.
# Import the libraries we need
# <-- Click the run icon
import json
import os
import altair as alt
import pandas as pd
import requests
from dotenv import load_dotenv
load_dotenv()
True
You need an API key to get data from Trove. Insert your key below.
# Insert your Trove API key
API_KEY = "YOUR API KEY"
# Use api key value from environment variables if it is available
if os.getenv("TROVE_API_KEY"):
API_KEY = os.getenv("TROVE_API_KEY")
Set up some default parameters for our API query.
# Set up default parameters for our API query
# <-- Click the run icon
params = {
"category": "newspaper",
"l-artType": "newspaper",
"encoding": "json",
"facet": "state",
"n": 0,
}
headers = {"X-API-KEY": API_KEY}
API_URL = "http://api.trove.nla.gov.au/v3/result"
Construct your search¶
This is where you set your search keywords. Change 'weather' in the cell below to anything you might enter in the Trove simple search box. For example:
params['q'] = 'weather AND wragge'
params['q'] = '"Clement Wragge"'
params['q'] = 'text:"White Australia Policy"'
params['q'] = 'weather AND date:[1890-01-01T00:00:00Z TO 1920-12-11T00:00:00Z]'
You can also limit the results to specific categories. To only search for articles, include this line:
params['l-category'] = 'Article'
# Enter your search parameters
# This can be anything you'd enter in the Trove simple search box
params["q"] = "drought"
# Remove the "#" symbol from the line below to limit the results to the article category
params["l-category"] = "Article"
# <-- Click the run icon
response = requests.get(API_URL, params=params, headers=headers)
data = response.json()
Reformat the results¶
# <-- Click the run icon
def format_facets(data):
facets = data["category"][0]["facets"]["facet"][0]["term"]
df = pd.DataFrame(facets)
df = df[["display", "count"]]
df.columns = ["state", "total"]
df["total"] = pd.to_numeric(df["total"], errors="coerce")
df = df.replace("ACT", "Australian Capital Territory")
df = df[(df["state"] != "National") & (df["state"] != "International")]
return df
df = format_facets(data)
df
state | total | |
---|---|---|
0 | New South Wales | 558970 |
1 | Queensland | 301702 |
2 | Victoria | 258701 |
3 | South Australia | 151862 |
4 | Western Australia | 85960 |
5 | Tasmania | 47622 |
6 | Australian Capital Territory | 13026 |
7 | Northern Territory | 1778 |
Make some charts!¶
Just run the cells!
# Create a bar chart
# <-- Click the run icon
chart = (
alt.Chart(df)
.mark_bar(color="#084081")
.encode(
x=alt.X("total", axis=alt.Axis(title="Total articles")),
y=alt.Y("state", axis=alt.Axis(title="")),
tooltip=[alt.Tooltip("total", title="Total articles")],
)
.properties(width=300, height=200)
)
# Make a chloropleth map
# <-- Click the run icon
with open("data/aus_state.geojson", "r") as geo_file:
geo_data = json.load(geo_file)
map = (
alt.Chart(alt.Data(values=geo_data["features"]))
.mark_geoshape(stroke="black", strokeWidth=0.2)
.encode(
color=alt.Color(
"total:Q",
scale=alt.Scale(scheme="greenblue"),
legend=alt.Legend(title="Total articles"),
)
)
.transform_lookup(
lookup="properties.STATE_NAME", from_=alt.LookupData(df, "state", ["total"])
)
.project(type="mercator")
.properties(width=400, height=400)
)
# Display the charts side by side
# <-- Click the run icon
alt.hconcat(map, chart).resolve_legend(color="independent")
Calculate proportions¶
Of course, this is just the raw number of results. Some states have more newspapers, so we have to be careful about making comparisons. This time we'll divide the number of search results for each state by the total number of articles published in that state to see what proportion our search represents. This should provide a more meaningful basis for comparison.
To calculate what proportion of the total number of articles the search results represent, we need to make another API request to find out how many articles were published over the same time frame. This time we'll leave the keywords out of the query. If you've set a date range, you'll want to keep it as the value for params['q']
. Otherwise remove the q
parameter completely using .pop()
, eg:
params.pop('q', None)
or
params['q'] = 'date:[* TO 1954]'
# params.pop("q", None)
params["q"] = "date:[* TO 1954]"
response = requests.get(API_URL, params=params, headers=headers)
total_data = response.json()
# Reformat the facets
total_df = format_facets(total_data)
# Merge the two dataframes, joining them on the 'state' column
df = pd.merge(df, total_df, on="state", how="left")
# Create a new column that contains the proportion of the total results this search represents
df["proportion"] = df["total_x"] / df["total_y"]
df
state | total_x | total_y | proportion | |
---|---|---|---|---|
0 | New South Wales | 558970 | 59704736 | 0.009362 |
1 | Queensland | 301702 | 29409712 | 0.010259 |
2 | Victoria | 258701 | 32163110 | 0.008043 |
3 | South Australia | 151862 | 16993879 | 0.008936 |
4 | Western Australia | 85960 | 16963973 | 0.005067 |
5 | Tasmania | 47622 | 11879580 | 0.004009 |
6 | Australian Capital Territory | 13026 | 553926 | 0.023516 |
7 | Northern Territory | 1778 | 294418 | 0.006039 |
Make some better charts!¶
Just run the cells!
# Create a bar chart
# <-- Click the run icon
chart2 = (
alt.Chart(df)
.mark_bar(color="#084081")
.encode(
x=alt.X("proportion", axis=alt.Axis(title="Proportion of articles")),
y=alt.Y("state", axis=alt.Axis(title="")),
tooltip=[alt.Tooltip("proportion", title="Proportion")],
)
.properties(width=300, height=200)
)
map2 = (
alt.Chart(alt.Data(values=geo_data["features"]))
.mark_geoshape(stroke="black", strokeWidth=0.2)
.encode(
color=alt.Color(
"proportion:Q",
scale=alt.Scale(scheme="greenblue"),
legend=alt.Legend(title="Proportion of articles"),
)
)
.transform_lookup(
lookup="properties.STATE_NAME",
from_=alt.LookupData(df, "state", ["proportion"]),
)
.project(type="mercator")
.properties(width=400, height=400)
)
# Display the charts side by side
# <-- Click the run icon
alt.hconcat(map2, chart2).resolve_legend(color="independent")
Created by Tim Sherratt for the GLAM Workbench.
Support this project by becoming a GitHub sponsor.