Skip to Content

Visualizing data with Simple Data Analysis and Plot

By Nael Shiab

Last updated on

Data visualizations help you understand your data and communicate your findings. In this lesson, we’ll learn how to visualize SDA tables, from simple terminal charts to customized visualizations with Observable Plot .

We’ll save our charts as PNG or SVG files in this lesson. However, Plot is a library built for the web, so you can reuse the code we write here to display a chart inside an HTML element on a web page. Isn’t TypeScript amazing? 😊

We’ll use data on the 2023 Canadian wildfires and explore different visualization techniques, including line charts, beeswarm charts, and maps! 🌎

This lesson assumes you’ve completed the Setup, Tabular data, and Geospatial data lessons.

Want to know when new lessons are available? Subscribe to the newsletter ✉️ and give a ⭐ to the GitHub repository to keep me motivated! Click here to get in touch.

Setup

Create a new empty folder somewhere handy on your computer and open it in VS Code. Then open the terminal in VS Code.

We’ll use @nshiab/setup-data-project, a library I created to install the libraries and set up all the files and configuration we need for a project. Run this command in the terminal:

npx @nshiab/setup-data-project --sda

If prompted to install the library, type y and press Enter.

The --sda option automatically selects the simple-data-analysis library for installation.

Once the terminal says You are all set!, open sda/main.ts. You’ll see some starter code in it.

VS Code showing the project files and the setup completion message.

If VS Code asks you to install the recommended Oxc extension, click Install. It helps format your code and find potential problems as you work.

VS Code recommending the Oxc extension, with an arrow pointing to Install.

We’re now ready to watch sda/main.ts. Run the command below. Every time you save the file, it will automatically format, check, and run your code:

npm run sda:watch

If you ever need to stop watching, click the terminal and press Ctrl+C on Mac or Windows.

Keep the watcher running while you work through this lesson.

Creating our helper functions

To keep our code organized, let’s create two functions:

  • crunchData, where we’ll fetch and clean the wildfire data.
  • visualizeData, where we’ll generate charts and maps.

Let’s start with crunchData. Create a crunchData.ts file in ./sda/helpers/. This async function will fetch and cache the wildfire data.

crunchData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; export default async function crunchData(fires: SimpleTable) { await fires.cache((table) => { table.loadData( "https://raw.githubusercontent.com/nshiab/data-fetch-lesson/refs/heads/main/reported_fires_2023.csv", ); }); }
💡

On the first run, SDA saves the table in .sda-cache. On later runs, it loads the table from there.

Now, we can take care of visualizeData. Create a visualizeData.ts file in ./sda/helpers/. For now, let’s just log the table.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); }

VS Code showing crunchData.ts and visualizeData.ts side by side and listed in the sda/helpers folder.

💡

To view multiple files side by side in VS Code, right-click a file tab and select Split Right. This is handy when you want to look at and work across multiple files at the same time.

Let’s update main.ts to create the fires table and pass it to our new functions.

main.ts
import { SimpleDB } from "@nshiab/simple-data-analysis"; import crunchData from "./helpers/crunchData.ts"; import visualizeData from "./helpers/visualizeData.ts"; const sdb = new SimpleDB(); const fires = sdb.newTable("fires"); await crunchData(fires); await visualizeData(fires); await sdb.close();

Don’t forget to save all three files (Command + S on macOS or Ctrl + S on Windows). You should then see the fires table in the terminal.

VS Code showing main.ts calling both helper functions and the first 10 rows of the fires table in the terminal.

Prepping the data

We have around 5,000 wildfires. Let’s say that we would like to visualize how much wildfires have burnt through the year, for each province. We need the cumulative sum of the area burnt.

In crunchData.ts, let’s sum up our fires per date and province.

crunchData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; export default async function crunchData(fires: SimpleTable) { await fires.cache((table) => { table.loadData( "https://raw.githubusercontent.com/nshiab/data-fetch-lesson/refs/heads/main/reported_fires_2023.csv", ); }); fires.summarize({ columns: "hectares", by: ["province", "startdate"], stats: "sum", }); }

Since we aggregated the data, we went from more than 5,000 rows to just over 1,000.

VS Code showing crunchData.ts summing hectares burned by province and start date, with the resulting table in the terminal.

Use accumulate to calculate the cumulative area burned for each province. Set decimals: 1 to round the results to one decimal place.

crunchData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; export default async function crunchData(fires: SimpleTable) { await fires.cache((table) => { table.loadData( "https://raw.githubusercontent.com/nshiab/data-fetch-lesson/refs/heads/main/reported_fires_2023.csv", ); }); fires .summarize({ columns: "hectares", by: ["province", "startdate"], stats: "sum", }) .accumulate("sum", "cumulativeHectares", { by: "province", decimals: 1, }); }

VS Code showing the accumulate call in crunchData.ts and the new cumulativeHectares column in the terminal.

Let’s visualize this data now!

In the terminal

SDA has some methods to easily log charts in your terminal. It’s a great way to quickly inspect your data. Let’s work in visualizeData.ts.

In the example below, we use the logDotChart method with the startdate column for the x values and cumulativeHectares for the y values. We also add two options:

  • We use the province values to create small multiples (one chart per province).
  • We make all the charts share the same scales, which is convenient for comparing provinces visually.
visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires.logDotChart("startdate", "cumulativeHectares", { smallMultiples: "province", fixedScales: true, }); }

VS Code showing the logDotChart call and four terminal dot charts of cumulative hectares burned, each for a different province and using the same scales.

You are not limited to dot charts. You can also use the methods logLineChart, logBarChart, and logHistogram.

However, while these methods are very handy, they are quite limited.

With Plot

Cumulative hectares burnt per province

Plot  is a fantastic library for creating charts. It’s based on the very famous d3  library (and built by the same team, including Mike Bostock  and Philippe Rivière ). However, it’s much easier to use because many things that need to be handled manually in d3 (scales, axes, etc.) are done automatically with Plot.

SDA integrates Plot seamlessly, and setup-data-project installs it automatically when you select SDA.

To create a chart and save it as a file (.png or .svg if you want to rework it in Illustrator), you can use the writeChart method.

The writeChart method requires two arguments:

  • A function that receives the table’s data and uses it to draw a Plot chart.
  • A path for the image file that will be saved.

In visualizeData.ts, let’s create a simple line chart showing the area burnt throughout 2023 for each province.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { line, plot } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires .writeChart( (data) => plot({ marks: [ line(data, { x: "startdate", y: "cumulativeHectares", stroke: "province", }), ], }), "./sda/output/chart.png", ); }

VS Code showing the writeChart code beside chart.png, a line chart of cumulative hectares burned by province in 2023.

💡

As a reminder, you can right-click a file tab or a file in the Explorer on the left and select Split Right to view several files, including images, side by side. Since the SDA task is watching main.ts, every time you update and save your code, the script runs automatically and refreshes the chart. Keeping the chart open next to your code lets you see your changes right away.

Let me explain what’s going on above:

  • On line 2, we import the line and plot functions from Plot.
  • On lines 6-19, we call writeChart on the fires table.
  • On line 8, we use data as the name for the rows the arrow function receives from fires.
  • On lines 9-17, we use plot to create the chart that the arrow function returns.
  • On line 10, we add a marks array. Marks are the shapes used to represent our data in a Plot chart.
  • On lines 11-15, we add a line mark. It uses startdate for the x values, cumulativeHectares for the y values, and province for the stroke color.
  • On line 18, we pass the second argument to writeChart, which specifies where the chart should be saved.

Our chart is quite basic for now, and there are some issues, like the y-axis. Let’s fix it!

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { line, plot } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires .writeChart( (data) => plot({ inset: 10, y: { grid: true, label: "Area burned (hectares)", ticks: 5, tickFormat: (d) => `${d / 1_000_000}M`, }, marks: [ line(data, { x: "startdate", y: "cumulativeHectares", stroke: "province", }), ], }), "./sda/output/chart.png", ); }

VS Code showing the y-axis options beside the line chart, with horizontal grid lines and tick labels in millions of hectares.

This is better! To update the y-axis, you can pass options to y as an object. Here’s what we are doing in the code above:

  • We add grids to make the chart more readable.
  • We format the top axis label to be more understandable with the unit.
  • We ask Plot for about five ticks.
  • We format the tick labels to show millions of hectares instead of just hectares.

I also added an inset of 10 to give a little more space to the top label.

Now, let’s update the x label. There’s no need to modify the x tick labels because Plot handles dates well, automatically displaying years, months, days, or even time based on the scale values and axis width.

The colors are currently assigned automatically. We can choose a different scheme and maybe add a legend.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { line, plot } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires .writeChart( (data) => plot({ inset: 10, y: { grid: true, label: "Area burned (hectares)", ticks: 5, tickFormat: (d) => `${d / 1_000_000}M`, }, x: { label: "Date", }, color: { legend: true, scheme: "tableau10", }, marks: [ line(data, { x: "startdate", y: "cumulativeHectares", stroke: "province", }), ], }), "./sda/output/chart.png", ); }

VS Code showing the x-axis and color options beside the line chart, with the x-axis labeled Date and a color legend above the chart.

Hmmmm… The color legend doesn’t work very well with so many categories. We need to change our strategy. Instead of a color legend, maybe we could add a dot and a text label at the end of each line.

Let’s remove the color legend and add a dot mark. Since we want to add dots at the end of each line, we use the selectLast transform. This will select only the last data point.

Note that the order in the marks array is important. Marks are drawn in sequence, so if you want a shape to appear on top of another, add it later in the array.

Don’t forget to remove legend: true from the color options! ⚠️

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { dot, line, plot, selectLast } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires .writeChart( (data) => plot({ inset: 10, y: { grid: true, label: "Area burned (hectares)", ticks: 5, tickFormat: (d) => `${d / 1_000_000}M`, }, x: { label: "Date", }, color: { scheme: "tableau10", }, marks: [ line(data, { x: "startdate", y: "cumulativeHectares", stroke: "province", }), dot( data, selectLast({ x: "startdate", y: "cumulativeHectares", fill: "province", }), ), ], }), "./sda/output/chart.png", ); }

VS Code showing the dot mark with selectLast beside the chart, where a colored dot marks the end of each line.

And now let’s add the text labels. We use selectLast again with some additional options:

  • We apply a black fill with a white stroke to improve readability, ensuring the text remains visible even when overlapping other chart elements.
  • We set textAnchor to start so the text aligns with the dot, but we shift it by 5 pixels with dx to prevent it from touching the dot.
  • We use x and y to position the labels, and z to create one label for each province. The text option uses the values in the province column for the labels.
visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { dot, line, plot, selectLast, text } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires .writeChart( (data) => plot({ inset: 10, y: { grid: true, label: "Area burned (hectares)", ticks: 5, tickFormat: (d) => `${d / 1_000_000}M`, }, x: { label: "Date", }, color: { scheme: "tableau10", }, marks: [ line(data, { x: "startdate", y: "cumulativeHectares", stroke: "province", }), dot( data, selectLast({ x: "startdate", y: "cumulativeHectares", fill: "province", }), ), text( data, selectLast({ text: "province", fill: "black", stroke: "white", textAnchor: "start", dx: 5, x: "startdate", y: "cumulativeHectares", z: "province", }), ), ], }), "./sda/output/chart.png", ); }

VS Code showing the text mark beside the line chart, with province names next to the dots at the ends of the lines.

This is much better! But our chart needs some obvious adjustments now.

For example, the dots and labels at the ends of the lines don’t align. We grouped fires by startdate, and the date of the last reported fire varies by province.

We also notice that not much is happening before mid-April and after October 1st.

Let’s go back to crunchData.ts to fix that:

  • On line 11, we filter the fires to keep only those with a startdate between April 15, 2023, and October 1, 2023.
  • After calculating the cumulative values, we remove the now-unneeded sum column.
  • Between lines 23 and 30, we use summarize to get each province’s maximum cumulative total in the filtered period. Then we use addColumn to assign that value to October 1 so the lines end on the same date.
  • Finally, on line 32, we insert these final values back into fires. Now, the data for every province has the same final date.
crunchData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; export default async function crunchData(fires: SimpleTable) { await fires.cache((table) => { table.loadData( "https://raw.githubusercontent.com/nshiab/data-fetch-lesson/refs/heads/main/reported_fires_2023.csv", ); }); fires .filter(`startdate >= '2023-04-15' && startdate <= '2023-10-01'`) .summarize({ columns: "hectares", by: ["province", "startdate"], stats: "sum", }) .accumulate("sum", "cumulativeHectares", { by: "province", decimals: 1, }) .removeColumns("sum"); const maxValuesPerProvince = fires .summarize({ columns: "cumulativeHectares", by: "province", stats: { cumulativeHectares: "max" }, outputTable: "maxValuesPerProvince", }) .addColumn("startdate", "date", `'2023-10-01'`); fires.insertTables(maxValuesPerProvince); }

VS Code showing the code that assigns October 1 to each province’s final value and the chart with its dots and labels aligned on that date.

And now, our labels are properly aligned!

Let’s go back to visualizeData.ts to fix the right margin. We can also filter out some labels to prevent overlapping text and add a caption explaining which labels are not shown.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { dot, line, plot, selectLast, text } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires .writeChart( (data) => plot({ caption: "Labels for provinces with less than 400,000 hectares burned are not shown.", inset: 10, marginRight: 110, y: { grid: true, label: "Area burned (hectares)", ticks: 5, tickFormat: (d) => `${d / 1_000_000}M`, }, x: { label: "Date", }, color: { scheme: "tableau10", }, marks: [ line(data, { x: "startdate", y: "cumulativeHectares", stroke: "province", }), dot( data, selectLast({ x: "startdate", y: "cumulativeHectares", fill: "province", }), ), text( data, selectLast({ text: "province", fill: "black", stroke: "white", textAnchor: "start", dx: 5, x: "startdate", y: "cumulativeHectares", z: "province", filter: (d) => d.cumulativeHectares >= 400_000, }), ), ], }), "./sda/output/chart.png", ); }

And here’s our chart! Pretty nice, isn’t it? 😊

VS Code showing the wider right margin and the line chart with labels for provinces with at least 400,000 hectares burned.

Of course, there’s much more you can do with Plot. Be sure to check the documentation  and the examples .

And if you want to create charts that can be modified in software like Illustrator, just save them as .svg instead of .png.

Wildfires beeswarm chart

Our previous chart was quite traditional, but you can also create more unconventional visualizations that push the boundaries of data storytelling.

For example, let’s create a beeswarm of our fires.

We can update crunchData.ts to return to our raw data. However, let’s keep only fires greater than 1 hectare. That leaves us with around 2,400 fires. This is quite a lot, considering we want to visualize each fire individually in this type of chart!

crunchData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; export default async function crunchData(fires: SimpleTable) { await fires.cache((table) => { table.loadData( "https://raw.githubusercontent.com/nshiab/data-fetch-lesson/refs/heads/main/reported_fires_2023.csv", ); }); fires.filter(`hectares > 1`); }

And let’s start by drawing our fires as simple dots on a y-axis.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { dot, plot } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires.writeChart( (data) => plot({ marks: [ dot(data, { y: "hectares" }), ], }), "./sda/output/chart.png", ); }

VS Code showing the dot mark beside a chart of wildfire sizes in hectares, with overlapping dots in a single vertical column.

Right now, our fires are overlapping. The purpose of a beeswarm chart is to stack data points in a way that ensures each one remains visible.

To create a beeswarm, we can use the dodgeX transform with the middle option. Let’s update our code.

Rendering this chart may take a few seconds, depending on your machine’s processing power.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { dodgeX, dot, plot } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires.writeChart( (data) => plot({ marks: [ dot( data, dodgeX("middle", { y: "hectares" }), ), ], }), "./sda/output/chart.png", ); }

VS Code showing the dodgeX call beside a beeswarm chart that spreads wildfire dots horizontally while keeping their height tied to hectares burned.

It looks like we have a looooot of small wildfires and a few very big ones.

A logarithmic scale could help with that! Let’s change our y scale type to log.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { dodgeX, dot, plot } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires.writeChart( (data) => plot({ y: { type: "log", }, marks: [ dot( data, dodgeX("middle", { y: "hectares" }), ), ], }), "./sda/output/chart.png", ); }

VS Code showing the log scale option beside the beeswarm chart, with y-axis labels at powers of ten.

This is already much better. Another improvement would be to scale the dot radius based on fire size.

We can update the options for the dot function and adjust the r scale to ensure a minimum radius of 1 pixel and a maximum of 20 pixels.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { dodgeX, dot, plot } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires.writeChart( (data) => plot({ y: { type: "log", }, r: { range: [1, 20], }, marks: [ dot( data, dodgeX("middle", { y: "hectares", r: "hectares" }), ), ], }), "./sda/output/chart.png", ); }

VS Code showing the radius settings beside the beeswarm chart, where larger circles represent fires that burned more hectares.

We are getting there.

Let’s fill the circles based on the cause of the fire and add a legend.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { dodgeX, dot, plot } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires.writeChart( (data) => plot({ y: { type: "log", }, r: { range: [1, 20], }, color: { legend: true, }, marks: [ dot( data, dodgeX("middle", { y: "hectares", r: "hectares", fill: "cause" }), ), ], }), "./sda/output/chart.png", ); }

VS Code showing the beeswarm chart colored by wildfire cause, with a legend for human, natural, and unknown causes.

To help compare the causes, we could use facets. Let’s do that to create three small charts instead of one large one.

To achieve this, we use the fx option to create horizontal facets. Let’s also increase the chart width for better readability.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { dodgeX, dot, plot } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires.writeChart( (data) => plot({ width: 800, y: { type: "log", }, r: { range: [1, 20], }, color: { legend: true, }, marks: [ dot( data, dodgeX( "middle", { y: "hectares", r: "hectares", fill: "cause", fx: "cause", }, ), ), ], }), "./sda/output/chart.png", ); }

VS Code showing the fx option beside three beeswarm panels for fires with human, natural, and unknown causes.

This is starting to look very good. We probably don’t need the color legend anymore.

Let’s tweak the labels and axes, then call it a day!

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { dodgeX, dot, plot } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires.writeChart( (data) => plot({ width: 800, marginTop: 40, y: { type: "log", label: "Hectares", ticks: 5, grid: true, }, r: { range: [1, 20], }, fx: { label: null, }, marks: [ dot( data, dodgeX( "middle", { y: "hectares", r: "hectares", fill: "cause", fx: "cause", }, ), ), ], }), "./sda/output/chart.png", ); }

This is quite nice, isn’t it? By playing with marks and transforms, you can create stunning data visualizations with SDA and Plot.

Again, I encourage you to check the Plot documentation  and examples . You’ll have a lot of fun with this library! 💃🕺

Final beeswarm chart comparing wildfire sizes on a logarithmic scale. The largest fires appear in the panel for natural causes.

Fires map

With SDA, you can work with both tabular and geospatial data. When wrangling geospatial data, you often want to create maps!

Let’s map our fires along with the Canadian province boundaries.

First, we need to store the fire geometries in the same table as the province boundaries.

Let’s reuse what we did in the previous lesson and update crunchData.ts. We’ll modify it to take a second table, provinces, as a parameter. For the fires, we create point geometries from the lat and lon columns. We also add an isFire column set to true.

Then, we fetch and cache the province boundaries and add the same isFire column, this time set to false. Finally, we insert the provinces into fires and use the unifyColumns option because the two tables do not have the same columns.

crunchData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; export default async function crunchData( fires: SimpleTable, provinces: SimpleTable, ) { await fires.cache(() => { fires .loadData( "https://raw.githubusercontent.com/nshiab/data-fetch-lesson/refs/heads/main/reported_fires_2023.csv", ) .createPoints("lat", "lon", "geom") .addColumn("isFire", "boolean", `TRUE`); }); await provinces.cache(() => { provinces.loadGeoData( "https://raw.githubusercontent.com/nshiab/simple-data-analysis/main/test/geodata/files/CanadianProvincesAndTerritories.json", ) .addColumn("isFire", "boolean", `FALSE`); }); fires.insertTables(provinces, { unifyColumns: true }); }

Let’s remove everything except the log in visualizeData.ts for now.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); }

And let’s update main.ts to create a new table provinces and pass it to crunchData.

main.ts
import { SimpleDB } from "@nshiab/simple-data-analysis"; import crunchData from "./helpers/crunchData.ts"; import visualizeData from "./helpers/visualizeData.ts"; const sdb = new SimpleDB(); const fires = sdb.newTable("fires"); const provinces = sdb.newTable("provinces"); await crunchData(fires, provinces); await visualizeData(fires); await sdb.close();

Here’s what you should see to start on the right foot.

You can see that the projection for the fires is EPSG:4326, which means it uses latitude and longitude. This is the right projection for what we want to do next.

You can also see that nameEnglish and nameFrench are null. This is because the fire data doesn’t have these columns. They come from the provinces table.

VS Code showing the first rows of the fires table in the terminal, with isFire set to true and both province name columns set to null.

If you want to see the provinces we inserted into fires, replace log with logBottom. This method shows the last 10 rows by default. Here, all the columns specific to fires are null because the provinces don’t have those values. However, nameEnglish and nameFrench are populated, and the geom column also has the correct EPSG:4326 projection. It’s always important to ensure that you’re using the right projection.

VS Code showing the last ten rows of the fires table, with isFire set to false and the English and French province and territory names filled in.

Now that we have all of the data in one table, it’s easy to call just one method to draw both the fires and the provincial boundaries. Let’s work on our map in visualizeData. Instead of using writeChart, we must use writeMap.

writeMap works just like writeChart. Its first parameter is a function that returns an Observable Plot chart, and its second parameter specifies where to write the chart.

There is one important difference. With writeChart, the data passed to the function was an array of objects. With writeMap, it is GeoJSON: a collection of features whose data is stored in each feature’s properties. You can see this on lines 8-13, where we use feature.properties.isFire to separate the fires from the provinces. On lines 16 and 17, we draw them separately with Observable Plot’s geo mark, which is designed to render geospatial features.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { geo, plot } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires .writeMap((geoData) => { const fires = geoData.features.filter( (feature) => feature.properties.isFire, ); const provinces = geoData.features.filter( (feature) => !feature.properties.isFire, ); return plot({ marks: [ geo(provinces), geo(fires), ], }); }, "./sda/output/map.png"); }

VS Code showing the writeMap code alongside map.png, with wildfire locations drawn as circles over Canada's provincial and territorial boundaries.

As you can see in the screenshot above, the geo mark automatically detected the point coordinates of our fires and the polygon coordinates of the Canadian province boundaries. Pretty clever! 🤓

So far, Plot has drawn longitude and latitude directly on the x and y axes. Let’s set a projection better suited to a map of Canada:

  • Set the type to conic-conformal.
  • Use the rotate option to properly align Canada within the projection.
  • Use the domain option to fit the full extent of our geospatial data within the map, taking up as much space as possible without being cut off.
visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { geo, plot } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires .writeMap((geoData) => { const fires = geoData.features.filter( (feature) => feature.properties.isFire, ); const provinces = geoData.features.filter( (feature) => !feature.properties.isFire, ); return plot({ projection: { type: "conic-conformal", rotate: [100, -60], domain: geoData, }, marks: [ geo(provinces), geo(fires), ], }); }, "./sda/output/map.png"); }

VS Code showing the conic conformal projection settings beside the resulting wildfire map of Canada.

This is looking better. I chose Observable Plot’s conic-conformal projection because it belongs to the same projection family commonly used by Natural Resources Canada and Statistics Canada for maps of Canada.

Let’s style our province boundaries to create a nice light background.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { geo, plot } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires .writeMap((geoData) => { const fires = geoData.features.filter( (feature) => feature.properties.isFire, ); const provinces = geoData.features.filter( (feature) => !feature.properties.isFire, ); return plot({ projection: { type: "conic-conformal", rotate: [100, -60], domain: geoData, }, marks: [ geo(provinces, { stroke: "lightgray", fill: "whitesmoke", }), geo(fires), ], }); }, "./sda/output/map.png"); }

VS Code showing the stroke and fill settings beside the wildfire map, where the provinces have a pale gray fill and light gray borders.

Now, let’s work on the fires. Since they are point geometries, Plot automatically represents them as dots using the geo mark.

But nothing stops us from using another mark! Let’s create a spike map instead. Spikes use a length property and a corresponding length scale. We set its range to [1, 100], so the spikes are between 1 and 100 pixels tall.

Because the fires are a collection of GeoJSON features, we need to use arrow functions to specify where Plot should find the right values for the spike options.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { geo, plot, spike } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires .writeMap((geoData) => { const fires = geoData.features.filter( (feature) => feature.properties.isFire, ); const provinces = geoData.features.filter( (feature) => !feature.properties.isFire, ); return plot({ projection: { type: "conic-conformal", rotate: [100, -60], domain: geoData, }, length: { range: [1, 100], }, marks: [ geo(provinces, { stroke: "lightgray", fill: "whitesmoke", }), spike(fires, { x: (d) => d.properties.lon, y: (d) => d.properties.lat, length: (d) => d.properties.hectares, }), ], }); }, "./sda/output/map.png"); }

VS Code showing the spike mark settings beside a map of Canada, where taller spikes represent wildfires that burned more hectares.

This is quite interesting! Now, let’s color-code the spikes based on the cause of the wildfires. Observable Plot assigns one color to each cause. Each spike uses that color for its outline and a translucent version for its fill, allowing us to see spikes that overlap.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { geo, plot, spike } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires .writeMap((geoData) => { const fires = geoData.features.filter( (feature) => feature.properties.isFire, ); const provinces = geoData.features.filter( (feature) => !feature.properties.isFire, ); return plot({ projection: { type: "conic-conformal", rotate: [100, -60], domain: geoData, }, length: { range: [1, 100], }, color: { legend: true, }, marks: [ geo(provinces, { stroke: "lightgray", fill: "whitesmoke", }), spike(fires, { x: (d) => d.properties.lon, y: (d) => d.properties.lat, length: (d) => d.properties.hectares, stroke: (d) => d.properties.cause, }), ], }); }, "./sda/output/map.png"); }

VS Code showing the wildfire spike map with a legend for human, natural, and unknown causes.

Adding colors helps, but many spikes still overlap. By default, Plot fills spikes with an opacity of 0.3. Transparency can be useful for revealing marks behind one another, but here the many overlapping fills create too much visual noise.

In the code below, we set fillOpacity to 1 and use lighter versions of the legend colors. Some spikes will hide others, but the map will be much easier to read. We also increase the maximum spike height from 100 to 200 pixels to make the differences more visible.

visualizeData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; import { geo, plot, spike } from "@observablehq/plot"; export default async function visualizeData(fires: SimpleTable) { await fires.log(); await fires .writeMap((geoData) => { const fires = geoData.features.filter( (feature) => feature.properties.isFire, ); const provinces = geoData.features.filter( (feature) => !feature.properties.isFire, ); return plot({ projection: { type: "conic-conformal", rotate: [100, -60], domain: geoData, }, length: { range: [1, 200], }, color: { legend: true, }, marks: [ geo(provinces, { stroke: "lightgray", fill: "whitesmoke", }), spike(fires, { x: (d) => d.properties.lon, y: (d) => d.properties.lat, length: (d) => d.properties.hectares, stroke: (d) => d.properties.cause, fillOpacity: 1, fill: (d) => { if (d.properties.cause === "Human") { return "#b5caff"; } else if (d.properties.cause === "Natural") { return "#ffe6a8"; } else { return "#ffb9ad"; } }, }), ], }); }, "./sda/output/map.png"); }
💡

There are many ways to represent colors. Here, I am using HEX color values. Read this  if you want to know more.

The screenshot shows the new fills with the maximum spike height still at 100 pixels.

VS Code showing fillOpacity set to 1 and lighter fill colors on the wildfire spikes.

There is one more adjustment to make now that the spikes are opaque: their drawing order. By default, Plot draws them in the order they appear in the data. Instead, we’ll order them by latitude so fires with a greater latitude (further north) are drawn first and fires with a smaller latitude (further south) appear in front. This adds some perspective to the map.

We can update crunchData to sort the fires by latitude in descending order. Thank you to Philippe Rivière  for the suggestion! 😊

crunchData.ts
import type { SimpleTable } from "@nshiab/simple-data-analysis"; export default async function crunchData( fires: SimpleTable, provinces: SimpleTable, ) { await fires.cache(() => { fires .loadData( "https://raw.githubusercontent.com/nshiab/data-fetch-lesson/refs/heads/main/reported_fires_2023.csv", ) .createPoints("lat", "lon", "geom") .addColumn("isFire", "boolean", `TRUE`); }); await provinces.cache(() => { provinces.loadGeoData( "https://raw.githubusercontent.com/nshiab/simple-data-analysis/main/test/geodata/files/CanadianProvincesAndTerritories.json", ) .addColumn("isFire", "boolean", `FALSE`); }); fires .insertTables(provinces, { unifyColumns: true }) .sort({ lat: "desc" }); }

This is looking great! To learn more about maps, check out the geo mark documentation as well as the projection documentation.

Our final spike map.

Conclusion

Congrats! You now know how to create data visualizations with SDA and Plot!

I hope the step-by-step examples helped you understand how to build everything from simple charts to more innovative ones using both tabular and geospatial data.

Here, we saved our visualizations as PNG images. If you change .png to .svg in the output path, you’ll get a vector version that you can customize further in software like Adobe Illustrator or use on a web page.

I chose Observable Plot for SDA because the same Plot code used throughout this lesson can also be reused directly on a web page. This makes your visualizations flexible, versatile, and easy to adapt for other projects.

Make sure to check the conclusion of this chapter for project ideas and suggestions on what to learn next.

Enjoyed this? Want to know when new lessons are available? Subscribe to the newsletter ✉️ and give a ⭐ to the GitHub repository to keep me motivated! Get in touch if you have any questions.