Published
Edited
Sep 12, 2021
Insert cell
Insert cell
vegalite = require("vega-embed@6")
Insert cell
Insert cell
//Gapminder dataset
gapminder = FileAttachment("gapminder.csv").csv({typed: true})
Insert cell
//mpg dataset
mpg=FileAttachment("mpg.csv").csv({typed: true})
Insert cell
Insert cell
Insert cell
//filters the data including only selected countries and label all others as 'Other countries'
newGapminder = gapminder.map(function(d,i){
let updatedCountry = (d.population < 200000000) ? "Other countries": d.country;
return{
country: updatedCountry,
continent: d.continent,
year: d.year,
lifeExp: d.lifeExp,
population: d.population,
gdpPerCap: d.gdpPerCap
}
})
.filter(d => d.year == 1987 || d.year === 1997 || d.year === 2007)
Insert cell
//Calculates the sum of population of countries which fall under 'Other countries' in year (1987)
sum1987 = newGapminder.reduce(function(sum,d){
let population = ( d.country === "Other countries" && d.year === 1987) ? d.population: 0;
return sum+ population;
},0)
Insert cell
//Calculates the sum of population of countries which fall under 'Other countries' in year (1997)
sum1997 = newGapminder.reduce(function(sum,d){
let population = ( d.country === "Other countries" && d.year === 1997) ? d.population: 0;
return sum+ population;
},0)
Insert cell
//Calculates the sum of population of countries which fall under 'Other countries' in year (2007)
sum2007 = newGapminder.reduce(function(sum,d){
let population = ( d.country === "Other countries" && d.year === 2007) ? d.population: 0;
return sum+ population;
},0)
Insert cell
//Extracts the dataset with country names other than those of 'Other countries'
newData = newGapminder.map(function(d,i){
if (d.country === "Other countries") return null;
return{
country: d.country,
population: d.population,
year: d.year
}
}).filter(d => d != null)
Insert cell
//Adds the corresponding entries of 'Other countries' in each year
updatedData =newData.concat({country: "Other countries", population: sum1987, year: 1987},{country: "Other countries", population: sum1997, year: 1997},{country: "Other countries", population: sum2007, year: 2007})
Insert cell
vegalite(
{
"data": {
"values": updatedData,
},
"transform": [
{
//We will be using joinaggregate which is a special case of the window transform where the frame is always [null, null], so you can use window transform, too and use frame as [null, null].
//The joinaggregate transform extends the input data objects with aggregate values in a new field.
//Link: https://vega.github.io/vega-lite/docs/joinaggregate.html
"joinaggregate": [{
"op": "sum",
"field": "population",
"as": "TotalPopulation" //output field's name of the sum operation on population data
}],
"groupby": ["year"], //do calculations seperately for each year
},
{
"calculate": "datum.population/datum.TotalPopulation",
"as": "Percentage"
}
],
"facet": {
"column": {"field": "year", "type": "nominal", "title": false,
"header": { "labelFontSize": 20, "labelPadding":20 }},
},
"spec": {
"encoding": {
"theta": {"field": "Percentage", "type": "quantitative", "stack": "zero", "tooltip": {"content": "data"}}, //"stack": "zero" or "stack": true is needed because it stacks with baseline offset at zero value of the scale. It is needed for proper alignment of the percentage with their respective part
"order": {"field": "Percentage", "type": "quantitative", "sort": "descending"}, //orders the arc of dounut chart by size
"color": {"field": "country", "type": "nominal"},
},
"layer": [
{
"mark": {"type": "arc", "innerRadius": 40, "tooltip": {"content": "data"}, "outerRadius": 80},
//specifying outer radius to fit our percentage data on the chart in proper position (like put label at a slight larger radius of the dounut outerradius)
},
{
"mark": {"type": "text", "radius": 100, "fontSize": 12},
"encoding": {
"text": {"field": "Percentage", "type": "quantitative", "format": ".1%", },
//format specifies that the percentage value is shown in 1 decimal point
}
}
],
"view": {"stroke": null},
},
"padding": 30,
"title": {"text": "Populations 1987/1997/2007", "align": "left", "fontSize": 25, "offset": 30},
}
)
Insert cell
Insert cell
Insert cell
//Extract rows whose value of 'country' column is 'China' in years 1987, 1997 and 2007
china = gapminder.filter(d=> (d.country === "China" && (d.year == 1987 || d.year === 1997 || d.year === 2007)))
Insert cell
//Extract rows whose value of 'country' column is 'India' in years 1987, 1997 and 2007
india = gapminder.filter(d=> (d.country === "India" && (d.year == 1987 || d.year === 1997 || d.year === 2007)))
Insert cell
//Extract rows whose value of 'country' column is 'United States' in years 1987, 1997 and 2007
us = gapminder.filter(d=> (d.country === "United States" && (d.year == 1987 || d.year === 1997 || d.year === 2007)))
Insert cell
//Merge all three dataset in a single dataset called countryData
countryData = china.concat(india).concat(us)
Insert cell
vegalite(
{
"height": 400,
"width" : 200,
"data": {
"values": countryData,
},
"transform": [
{
"joinaggregate": [{
"op": "sum",
"field": "population",
"as": "TotalPopulation"
}],
"groupby": ["year"],
},
{
"calculate": "datum.population/datum.TotalPopulation",
"as": "Percentage"
}
],
"facet": {
"column": {"field": "year", "type": "nominal", "title": false,
"header": { "labelFontSize": 20, "labelPadding":20 }},
},
"spec": {
"encoding": {
"y": {"field": "population", "type": "quantitative","title": "Population→"},
"order": {"field": "population", "type": "quantitative", "sort": "descending"}, //For the sort-order you use here, make sure you order the corresponding y-field of the dataset in the same sort-order
"color": {"field": "country", "type": "nominal",
"sort": [ "United States", "India", "China"], //orders the position of label in the specified way
},
},
"layer": [
{
"mark": {type: "bar", width: 100, tooltip: true},
},
{
transform: [
{
"window": [{"op": "sum", "field": "population", "as": "testsum"}],
"groupby": ["year"],
},
{
"calculate": " datum.testsum - datum.population/2",
//datum.testsum represents the topmost position of each individual bars of the stacked-bar, then for each of those bars, subtracting {(population of each bar)/2} from the top position gives the mid-point of each individual bars of that stacked-bar.
"as": "center"
},
],
"mark": {"type": "text", "fontSize": 15},
"encoding": {
"color": {"value": "white"},
"y": {"field": "center", "type": "quantitative", "title": false},
"text": {"field": "Percentage", "type": "quantitative", "format": ".1%"},
"order": {"field": "Percentage", "type": "quantitative", "sort": "descending"}, //orders inside the stacked bar chart
},
}
],
"view": {"stroke": null},
},
"padding": 30,
"title": {"text": "Populations 1987/1997/2007", "align": "left", "fontSize": 25, "offset": 30},
}
)
Insert cell
Insert cell
Insert cell
vegalite(
{
"data": {
"values": countryData,
},
"transform": [
{
"joinaggregate": [{
"op": "sum",
"field": "population",
"as": "TotalPopulation"
}],
"groupby": ["year"],
},
{
"calculate": "datum.population/datum.TotalPopulation",
"as": "Percentage"
}
],
"facet":
{
"column": {"field": "year", "type": "nominal", "title": false,
"header": { "labelFontSize": 20, "labelPadding":20 }},
},
"spec":
{
"encoding": {
"x": {"field": "country", "type": "ordinal", "axis": false}, //Adding this row creates a grouped bar-chart in a already existing stacked bar-chart
"y": {"field": "population", "type": "quantitative", "title": "Population→"},
"order": {"field": "population", "type": "quantitative", "sort": "descending"},
"color": {"field": "country", "type": "nominal", "title": "Country"},
},
"layer": [
{
"mark": {type: "bar", tooltip: true},
},
{
"mark": {"type": "text", "baseline": "bottom", "fontSize": 15},
"encoding": {
"color": {"value": "black"},
"text": {"field": "Percentage", "type": "quantitative", "format": ".1%"},
},
}
],
"view": {"stroke": null},
"width": 300,
},
"padding": 30,
"title": {"text": "Populations 1987/1997/2007", "align": "left", "fontSize": 25, "offset": 30},
}
)
Insert cell
Insert cell
Insert cell
vegalite(
{
"data": {"values": mpg},
"mark": {"type": "point", "filled": true, "size": 100, "tooltip": {"content": "data"}},
"width": 600,
"height": 300,
"encoding": {
"x": {"field": "weight", "type": "quantitative", "scale": {"zero": false}, "title": "Weight→"},
//for quantitative data, setting "zero" false in "scale", so the generated plot covers most space of the canvas
"y": {"field": "mpg", "type": "quantitative", "scale": {"zero": false}, "title": "mpg→"},
"color": {"field": "origin", "title": "Origins"},
}
}
)
Insert cell
Insert cell
Insert cell
vegalite(
{
"data": {"values": mpg},
"width": 500,
"height": 300,
"encoding": {
"x": {
"field": "model_year",
"title": "Model_year→",
"axis": {"labelAngle": 0} //displays the x-axis label values horizontally
// "timeUnit": "year" //displays the complete year like 1970,...
}
},
"layer": [
{
"mark": {"type": "errorband", "extent": "ci"}, //by default, it is 95%CI
"encoding": {
"y": { "field": "mpg", "type": "quantitative", "title": "mpg→", "scale": {"zero": false}}
}
},
{
"mark": "line", //replacing "line" by "point" helps to figure out what points are joined to make the line
"encoding": {
"y": { "aggregate": "mean", "field": "mpg"} //calculates the mean of mpg values
}
}
]
})
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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