Published
Edited
Nov 11, 2019
Insert cell
md`# Importing external data
This notebook explains how to import external data, like CSV files to visualize it using Vega Lite
<figure>${Object.assign(await FileAttachment("import-data.png").image(), { alt: 'Hello World', style: 'width: 100%; max-width: 740px;' })}</figure>
`
Insert cell
md`First we need to import d3 fetch functionality in order to retrieve data from external sources`
Insert cell
d3 = require("d3-fetch@1")
Insert cell
md`Then we query the data using its available URL, in this case we are using data from Vega Lite data samples`
Insert cell
data = d3.csv("https://vega.github.io/vega-lite/data/seattle-weather.csv")
Insert cell
md`Now we need to import vega-lite library to create some visualizations using the data previously loaded`
Insert cell
vegalite = require("@observablehq/vega-lite@0.2")
Insert cell
md`## Time to visualize!
We create a very simple spec to inspect the data`
Insert cell
vegalite({
data: {values: data},
mark: "circle",
encoding: {
x: {field: "precipitation", type: "quantitative"}
}
})
Insert cell
md`As we can see, the vast majority of records are located between 0-20`
Insert cell
md`We can also show how many records have the same precipitation, using the y axis to reflect the count of occurences`
Insert cell
vegalite({
data: {values: data},
mark: "circle",
encoding: {
x: {aggregate: "count", field: "*", type: "quantitative"},
y: {field: "precipitation", type: "quantitative"}
}
})
Insert cell
md`As we can see, there are more than 800 records with 0 precipitation value and the rest distributes normally across the x axis, having the greatest precipitation in 55.9`
Insert cell
md`We can group the records using the 'bin' property on the x axis`
Insert cell
vegalite({
data: {values: data},
mark: "circle",
encoding: {
x: {aggregate: "count", field: "*", type: "quantitative"},
y: {bin:true, field: "precipitation", type: "quantitative"}
}
})
Insert cell
md`But in the case we have grouped results, its better to present them using bars and giving more space to see small values declaring 'width' property of the resulting visualization`
Insert cell
vegalite({
data: {values: data},
mark: "bar",
encoding: {
x: {aggregate: "count", field: "*", type: "quantitative"},
y: {bin:true, field: "precipitation", type: "quantitative"}
},
'width': 600
})
Insert cell
md`We now get a more clear picture and see that most of the precipitation values are between 0 and 10, which corresponds to the lower bar`
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more