Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
1a915a1
Datawrapper loader example
palewire Aug 17, 2024
51b4209
Delete examples/loader-datawrapper/Pipfile
palewire Aug 17, 2024
f4318ac
add the resulting asset in the repo, so we can build it without havin…
Fil Aug 19, 2024
269bd86
link in the examples list
Fil Aug 19, 2024
30919d4
data/chart.html
Fil Aug 19, 2024
0903ddd
Merge branch 'main' into datawrapper-example
palewire Aug 19, 2024
e98f242
Update examples/loader-datawrapper/requirements.txt
palewire Aug 19, 2024
c2c0bf8
Fixes
palewire Aug 19, 2024
4257f14
Update examples/loader-datawrapper/src/data/chart.html.py
palewire Aug 19, 2024
d8d0c17
Change chart
palewire Aug 19, 2024
0754b1c
Trim
palewire Aug 19, 2024
cda1154
Update yarn.lock
palewire Aug 19, 2024
d756ada
a helper for responsive dark mode and height
Fil Aug 21, 2024
6e6ce4b
show the code
Fil Aug 21, 2024
04ab679
override the dark=auto parameter if we pass dark=false
Fil Aug 21, 2024
32a1691
Add dark mode config
palewire Aug 21, 2024
56a06ff
Merge branch 'main' into datawrapper-example
palewire Aug 21, 2024
05d8ddd
Web component
palewire Aug 23, 2024
7c2b1e3
get or create chart
palewire Aug 23, 2024
aa01fed
Merge branch 'main' into datawrapper-example
palewire Aug 23, 2024
dfb3b5d
Add chart.txt to cache this for the example site
palewire Aug 23, 2024
c501f96
Merge branch 'datawrapper-example' of https://github.com/palewire/fra…
palewire Aug 23, 2024
2d559bb
Rename as datawrapper-api
palewire Aug 23, 2024
5c44d33
Rename as datawrapper-api
palewire Aug 23, 2024
34f6f2f
Rename as datawrapper-api
palewire Aug 23, 2024
0c9d940
Start with a simple example
palewire Aug 23, 2024
c8c56b3
dark mode edits, helper function
Fil Aug 23, 2024
20a75ab
Merge branch 'main' into datawrapper-example
palewire Aug 26, 2024
23ea365
Merge branch 'main' into datawrapper-example
Fil Aug 26, 2024
b07b608
wording
Fil Aug 26, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@

- [`chess`](https://observablehq.observablehq.cloud/framework-example-chess/) - Load Zip data from FIDE; create a bump chart with Observable Plot
- [`custom-stylesheet`](https://observablehq.observablehq.cloud/framework-example-custom-stylesheet/) - Define a custom stylesheet (custom theme)
- [`datawrapper-api`](https://observablehq.observablehq.cloud/framework-example-datawrapper-api/) - Create a chart with the Datawrapper API and embed it in your page
- [`google-analytics`](https://observablehq.observablehq.cloud/framework-example-google-analytics/) - A Google Analytics dashboard with numbers and charts
- [`hello-world`](https://observablehq.observablehq.cloud/framework-example-hello-world/) - A minimal Framework project
- [`intersection-observer`](https://observablehq.observablehq.cloud/framework-example-intersection-observer/) - Scrollytelling with IntersectionObserver
Expand Down
6 changes: 6 additions & 0 deletions examples/datawrapper-api/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
*.pyc
.DS_Store
.venv
/dist/
node_modules/
yarn-error.log
9 changes: 9 additions & 0 deletions examples/datawrapper-api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[Framework examples →](../)

# Datawrapper API

View live: <https://observablehq.observablehq.cloud/framework-example-datawrapper-api/>

This Observable Framework example demonstrates how to embed a [Datawrapper](https://www.datawrapper.de/) chart in your page, and write a data loader in Python to generate a new one.

The data loader lives in [`src/data/chart.txt.py`](./src/data/chart.txt.py).
3 changes: 3 additions & 0 deletions examples/datawrapper-api/observablehq.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
root: "src"
};
20 changes: 20 additions & 0 deletions examples/datawrapper-api/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"type": "module",
"private": true,
"scripts": {
"clean": "rimraf src/.observablehq/cache",
"build": "rimraf dist && observable build",
"dev": "observable preview",
"deploy": "observable deploy",
"observable": "observable"
},
"dependencies": {
"@observablehq/framework": "^1.7.0"
},
"devDependencies": {
"rimraf": "^5.0.5"
},
"engines": {
"node": ">=18"
}
}
2 changes: 2 additions & 0 deletions examples/datawrapper-api/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pandas
datawrapper
1 change: 1 addition & 0 deletions examples/datawrapper-api/src/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/.observablehq/cache/
20 changes: 20 additions & 0 deletions examples/datawrapper-api/src/data/chart.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Country,Combined,Male,Female
1st: Monaco :mc:,53.1,51.7,54.5
2nd: Japan :jp:,47.3,46,48.7
3rd: Germany :de:,47.1,46,48.2
Italy :it:,45.5,44.4,46.5
Greece :gr:,44.5,43.5,45.6
Hong Kong :hk:,44.4,43.5,45
Austria :at:,44,42.8,45.1
Spain :es:,42.7,41.5,43.9
Netherlands :nl:,42.6,41.5,43.6
Finland :fi:,42.5,40.9,44.3
South Korea :kr:,41.8,40.2,43.4
France :fr:,41.4,39.6,43.1
Poland :pl:,40.7,39,42.4
United Kingdom :gb:,40.5,39.3,41.7
Russia :ru:,39.6,36.6,42.5
Norway :no:,39.2,38.4,40
United States :us:,38.1,36.8,39.4
New Zealand :nz:,37.9,37.1,38.8
China :cn:,37.4,36.5,38.4
1 change: 1 addition & 0 deletions examples/datawrapper-api/src/data/chart.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
XA2EM
74 changes: 74 additions & 0 deletions examples/datawrapper-api/src/data/chart.txt.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import sys

import pandas as pd
from datawrapper import Datawrapper

# Read in the data file, which is drawn from a Datawrapper example
# https://academy.datawrapper.de/article/281-examples-of-datawrapper-dot-charts
df = pd.read_csv("src/data/chart.csv")

# Connect to the Datawrapper api
dw = Datawrapper()

# Search if the chart already exists
title = "Germany is the third-oldest country in the world"
search_result = dw.get_charts(search=title)

# If the chart already exists, return its id
if search_result['list']:
chart_id = search_result['list'][0]["id"]
sys.stdout.write(chart_id)
sys.exit()

# If it doesn't exist, create the chart
chart_config = dw.create_chart(
# Headline the chart
title=title,
# Set the type
chart_type="d3-dot-plot",
# Give the data
data=df,
# Configure everything about the chart
metadata={
# Set the description
"describe": {
"intro": "Median age in the three countries with the oldest population and selected other countries, in years",
"source-name": "Estimates by the CIA World Factbook, 2018",
"source-url": "https://www.cia.gov/library/publications/resources/the-world-factbook/fields/343rank.html",
},
# Configure the chart
"visualize": {
"custom-range": [
"35",
"55"
],
"range-extent": "custom",
"highlight-range": True,
"replace-flags": {
"style": "4x3",
"enabled": True
},
"color-by-column": True,
"show-color-key": True,
"color-category": {
"map": {
"Male": "#94c4d1",
"Female": "#ffca76",
"Combined": "#545a5d"
},
},
},
"publish": {
"autoDarkMode": True,
},
}
)

# Pull out the chart's unique identifier
chart_id = chart_config["id"]

# Publish the chart
dw.publish_chart(chart_id)

# Write the chart's unique identifier to stdout
sys.stdout.write(chart_id)
135 changes: 135 additions & 0 deletions examples/datawrapper-api/src/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# Datawrapper API

Datawrapper charts can be embedded in Framework using the chartmaker’s [web components](https://blog.datawrapper.de/web-component-embedding/) service. All that’s required is a published chart’s identifier.

## Simple embedding

<div class="card" style="max-width: 908px;">${DatawrapperChart("OuHrk")}</div>

For example, the chart above (from [this blog post](https://blog.datawrapper.de/spotify-music-trends/)) has the identifier `OuHrk`. To embed it in the page, just include this helper:

```js echo
function DatawrapperChart(chartId) {
const src = `https://datawrapper.dwcdn.net/${chartId}/embed.js`;
const div = document.createElement("div");
const tag = document.createElement("script");
tag.setAttribute("data-dark", dark);
tag.setAttribute("src", src);
div.append(tag);
return div;
}
```

then you can call:

```html run=false
<div class="card" style="max-width: 908px;">${embedDatawrapperChart("OuHrk")}</div>
```

<div class="tip">

This function is designed to keep your charts in sync with Framework’s [dark mode](https://observablehq.com/framework/lib/generators#dark).

</div>

## Using a data loader

You can dynamically generate charts with a Python data loader that uses the [Datawrapper API](https://datawrapper.readthedocs.io/en/latest/). The loader will return the chart’s unique identifier, which you can then use to embed the chart in your page.

```python
import sys

import pandas as pd
from datawrapper import Datawrapper

# Read in the data file, which is drawn from a Datawrapper example
# https://academy.datawrapper.de/article/281-examples-of-datawrapper-dot-charts
df = pd.read_csv("src/data/chart.csv")

# Connect to the Datawrapper api
dw = Datawrapper()

# Search if the chart already exists
title = "Germany is the third-oldest country in the world"
search_result = dw.get_charts(search=title)

# If the chart already exists, return its id
if search_result['list']:
chart_id = search_result['list'][0]["id"]
sys.stdout.write(chart_id)
sys.exit()

# If it doesn't exist, create the chart
chart_config = dw.create_chart(
# Headline the chart
title=title,
# Set the type
chart_type="d3-dot-plot",
# Give the data
data=df,
# Configure everything about the chart
metadata={
# Set the description
"describe": {
"intro": "Median age in the three countries with the oldest population and selected other countries, in years",
"source-name": "Estimates by the CIA World Factbook, 2018",
"source-url": "https://www.cia.gov/library/publications/resources/the-world-factbook/fields/343rank.html",
},
# Configure the chart
"visualize": {
"custom-range": [
"35",
"55"
],
"range-extent": "custom",
"highlight-range": True,
"replace-flags": {
"style": "4x3",
"enabled": True
},
"color-by-column": True,
"show-color-key": True,
"color-category": {
"map": {
"Male": "#94c4d1",
"Female": "#ffca76",
"Combined": "#545a5d"
},
},
},
"publish": {
"autoDarkMode": True,
},
}
)

# Pull out the chart's unique identifier
chart_id = chart_config["id"]

# Publish the chart
dw.publish_chart(chart_id)

# Write the chart's unique identifier to stdout
sys.stdout.write(chart_id)
```

<div class="note">

You’ll also need python3 and the [`pandas`](https://pypi.org/project/pandas/) and [`datawrapper`](https://pypi.org/project/datawrapper/) modules installed and available on your `$PATH`.

We recommend using a [Python virtual environment](https://observablehq.com/framework/loaders#venv), such as with venv or uv, and managing required packages via `requirements.txt` rather than installing them globally.

You will also need to create an API token with [Datawrapper](https://www.datawrapper.de/) and set it as an environment variable named `DATAWRAPPER_ACCESS_TOKEN`. You can learn how by visiting the site's [“Getting Started” guide](https://developer.datawrapper.de/docs/getting-started). You'll want to give the token permission to create and publish charts (see the [reference documentation](https://developer.datawrapper.de/reference/postchartsidpublish) for details).
</div>

The above data loader lives in `data/chart.txt.py`, and creates the `data/chart.txt` file attachment, which contains the identifier. We read this file’s contents and pass it to the helper:

```html echo
<div class="card" style="max-width: 908px;">${DatawrapperChart(await FileAttachment("data/chart.txt").text())}</div>
```

or, more simply:

```js echo run=false
DatawrapperChart(await FileAttachment("data/chart.txt").text())
```