Public
Edited
Apr 30, 2024
Importers
Insert cell
Insert cell
Insert cell
// https://www.nytimes.com/interactive/2024/01/01/world/asia/japan-earthquake-map.html
// source https://ultimosismo.igp.gob.pe/descargar-datos-sismicos
Insert cell
magnitude = 5.5
Insert cell
Insert cell
Insert cell
Insert cell
dataHist[0].utcDate
Insert cell
data.filter(d => d.eventId == 23752)
Insert cell
Insert cell
//index = d3.rollup(data, ([d]) => +d.magnitude, d => d.id, d => d.utcDate2)
//positions = new Map(d3.groups(data, d => d.id).map(([id, [d]]) => [id, [d.lon, d.lat]]).filter(([, position]) => position))
//names = new Map(d3.groups(data, d => d.id).map(([id, [d]]) => [id, `${d.levelName4}, ${d.levelName3}`]))
//dates = Array.from(d3.group(data, d => d.utcDate2).keys())
//frames = new Map(d3.pairs(dates, (a, b) => [b, Array.from(index, ([id, data]) => [id, Math.max(0, (data.get(b) || 0) - (data.get(a) || 0), 0)])]))
Insert cell
Insert cell
pe = d3.json("https://cdn.jsdelivr.net/npm/latam-atlas@0.0.4/files/peru-100k.json")
Insert cell
features = topojson.feature(pe, pe.objects.level2)
Insert cell
districts = topojson.feature(pe, pe.objects.level4)
Insert cell
provinces = topojson.feature(pe, pe.objects.level3)
Insert cell
departments = topojson.feature(pe, pe.objects.level2)
Insert cell
borders = topojson.mesh(pe, pe.objects.level4, (a, b) => a == b)
Insert cell
segmentation = ([
{depth: 70, color: "#efedf5"},
{depth: 300, color: "#bcbddc"},
{depth: 700, color: "#756bb1"},
])
Insert cell
/*quakeDepthCategory = {
return d3.scaleThreshold()
.domain(segmentation.map(d => d.magnitude))
.range(segmentation.map(d => d.category))
}*/
Insert cell
depthScale = d3.scaleThreshold()
.domain(segmentation.map(d => d.depth))
.range(segmentation.map(d => d.color))
Insert cell
depthScale(69.999)
Insert cell
depthScale_ = d3.scaleThreshold()
.domain(segmentation.map(d => d.depth))
.range(segmentation.map(d => d.color))

Insert cell
depthScale_(60.99)
Insert cell
maxRadius = 1000
Insert cell
// Mw moment magnitude
// M6 is 31.62 times M5. For visualization purpuses we took 10, related of an increase of amplitude between each scale.
function powerScale(
magnitude,
timesPerScale = 30,
maxMagnitude = 10,
) {
const maxPower = Math.pow(timesPerScale, maxMagnitude)
const scaler = d3.scaleSqrt().domain([0, maxPower]).range([0, maxRadius])
return scaler(Math.pow(timesPerScale, magnitude))
}
Insert cell
Math.pow(powerScale(7), 2) / Math.pow(powerScale(7-1), 2)
Insert cell
powerScale(9)
Insert cell
powerScale(10)
Insert cell
// Barranca, Casma, Ocoña, Pisco
nanData = data.filter(d => d.magnitude >= 7.8)
Insert cell
Insert cell
layout
Insert cell
Insert cell
// use a cell reference so observable waits for the dom before render.
svgCell = {
return html`
<svg width=${width} height=${height} style="background-color:#d1e5f0" >
<g class="map" transform="translate(100, 20)"></g>
<g class="legendcl" transform="translate(0, ${innerHeight - 360})"></g>
<g class="legendbar" transform="translate(80, ${innerHeight + 30})"></g>
<circle r="10" stroke="red" fill="none" cx=585 cy=1024></circle>
</svg>
`}
Insert cell
html `<style type="text/css">
svg {
font-family: serif;
font-size: 12mm;
fill: navy;
}
.em {
fill: royalBlue;
}
.strong {
stroke: navy;
font-style: italic;
}
</style>`
Insert cell
html `<text x="5mm" y="2.1cm" >One,
<tspan class="em" dy="-0.5cm">Two,</tspan>
<tspan class="strong em" dy="-0.5cm">Three!</tspan>
</text>
`
Insert cell
atico = data.filter(d => d.magnitude > 8)
Insert cell
typeof(svgCell)
Insert cell
Insert cell
Insert cell
circleLegend(circleLegendArray, { // pass in array of values (e.g. min,mean/median & max)
// overide defaults
svg: d3.select(svgCell).select('g.legendcl'),
domain: [0, 9],
range: [0, 190], // 190 pixel is 9 earthquake
scale: powerScale,
title: "Magnitude (M)",
})
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function mapChart(data, {
svg,
projection,
feature,
border,
colorScale,
radiusScale,
colorBy,
radiusBy,
thresholdBigMagnitude = 8,
thresholdMidMagnitude = 7.8
} = {}) {

const path = d3.geoPath(projection)

/* const svg = d3.create('svg')
.attr('viewBox', `0, 0, ${width}, ${height}`)*/
// add map
const innerChart = svg
.append('g')
.attr('transform', `translate(0, 0)`)
.attr('class', 'map')
innerChart
.append('g')
.attr('class', 'map-features')
.selectAll('path')
.data(feature.features)
.join('path') // enter().append('path')
.attr('d', path)
.attr('fill', '#ddd')
innerChart
.append('g')
.attr('class', 'map-borders')
.selectAll('path')
.data(border.features)
.join('path')
.attr('d', path)
.attr('fill', 'none')
.attr('stroke', 'gray')
.attr('stroke-width', 0.25)
.attr('stroke-linejoin', 'round')
.attr('pointer-events', 'none')

// Add data
let circleG = innerChart
.append('g')
.attr('class', 'map-data')
.selectAll(null)
.data(data, d => d.eventId)
.join('g')
.attr('transform', d => {
return "translate(" + projection(d.geometry.coordinates) + ")"
})

// add circles
circleG
.append('circle')
.attr('stroke', 'black')
.attr('fill-opacity', 0.8)
.attr('stroke-width', d => d.magnitude >= thresholdBigMagnitude ? 2 : 0.3) //
.attr('fill', d => colorScale(d[colorBy])) //
.attr("r", d => radiusScale(d[radiusBy])) //

// add text
const textCircles = circleG
.append('text')
.attr('text-anchor', "end")
.style("font-size", "15px")
.attr("x", 0)
.attr('y', 0)
.attr('stroke-width', 0.25)
.attr('text-anchor', 'middle')
.attr('stroke', d => {
return d.magnitude >= thresholdBigMagnitude ? 'black'
: d.magnitude >= thresholdMidMagnitude ? '#f0f0f0' : null})

textCircles
.append('tspan')
.attr('y', d => - (radiusScale(d[radiusBy]) + 20))
.text(d => {
const title = `M${format(d[radiusBy])}, ${d.year}`
return d.magnitude >= thresholdMidMagnitude ? title : null
})
textCircles
.append('tspan')
//.attr('text-anchor', 'middle')
.attr('x', d => {
const title = `${d.description}, ${d.department}`
return - (title.length - 10)
})
.attr('y', d => - (radiusScale(d[radiusBy]) + 5))
.text(d => {
const title = `${d.description}, ${d.department}`
return d.magnitude >= thresholdMidMagnitude ? title : null
})
// add lines guides
/*circleG.append('line')
.attr('stroke', d => {
return d.magnitude >= thresholdBigMagnitude ? 'black'
: d.magnitude >= thresholdMidMagnitude ? 'gray' : null})
.attr('x1', 0)
.attr('y1', 0)
.attr('x2', -40)
.attr('y2', -30)*/
return svg.node()
}
Insert cell
data
Insert cell
format = d3.format(".1f")
Insert cell
projection = {
const scale = 2000
//return d3.geoMercator().scale(scale).translate([3/2 * scale, 30])
return d3.geoIdentity().reflectY(true).fitSize([innerWidth, innerHeight], features)
}
Insert cell
Insert cell
innerWidth = width - margin.left - margin.right
Insert cell
innerHeight = height - margin.top - margin.bottom
Insert cell
//width = 900
Insert cell
width
Insert cell
height = 4/3 * width
Insert cell
Insert cell
/*html`
<style>

.sphere {
fill: #bbb;
}

.land {
fill: #666;
}

.boundry {
fill: none;
stroke: #bbb;
stroke-linejoin: round;
stroke-linecap: round;
vector-effect: non-scaling-stroke;
}

.overlay {
fill: none;
pointer-events: all;
}
</style>
`*/
Insert cell
Insert cell
Insert cell
array = [{ id: 1, value: 'a' }, { id: 2, value: 'b' }]
Insert cell
newArray = array.map(obj => {
if (obj.id === 1) {
return { ...obj, value: 'c' };
}
return obj;
});
Insert cell
piscoEqId = data.filter(d => d.magnitude >= 7.8 && d.year === 2007)[0].eventId
Insert cell
data_ = data.map(obj => {
if (obj.eventId === piscoEqId) {
return {
...obj,
distanceFromCoast: '40',
department: 'Ica',
description: 'Pisco'
}
}
return obj
})
Insert cell
data_.filter(d => d.even)
Insert cell
// // 2023-12-07 16:23:44 (UTC) // 1701966224580
// testing
{
const testh = "2023-12-07" + " " + "16:23:44.00".slice(0, 8) + " -0500"
const parseUtc = d3.utcParse("%Y-%m-%d %H:%M:%S %Z")
return parseUtc(testh).getTime()
}
Insert cell
// A day in miliseconds
{
const dateObj = new Date();
return dateObj.setDate(dateObj.getDate()) - dateObj.setDate(dateObj.getDate()-1)
}
Insert cell
Insert cell
// how to replace "/" with "-"
{ const s = "20/05/1973"
return s.replace(/[/]/g, x => ({"/": "-"})[x])
}
Insert cell
array2 = [
{ id: 1, name: "-" },
{ id: 2, name: "7.4" },
{ id: 4, name: "7.1" },
{ id: 5, name: "5.1" },
// ... more objects
]
Insert cell
// replace(/[-]/g, x => ({"-": ""})[x])
array2.map(obj => {
return {
...obj,
name2: obj.name.includes("-") ? obj.name.replace(/[-]/g, "") : obj.name // Replace "-" with "_"
};
}).map(d => {
return {
...d,
name2: +d.name2,
}
})
Insert cell
powerScale(test)
Insert cell
test = 9
Insert cell
Insert cell
circleSvgH = innerCircleHeight + margin.top + margin.bottom
Insert cell
innerCircleWidth = 4 * powerScale(9)
Insert cell
innerCircleHeight = 2 * powerScale(9)
Insert cell
{return html`<svg width=${circleSvgW } height=${circleSvgH} style="background-color:cyan">
<circle cx=${innerCircleWidth /4} cy=${circleSvgH/2} r=${powerScale(test)} fill="green" opacity=0.4></circle>
<circle cx=${innerCircleWidth * 3/4} cy=${circleSvgH/2} r=${powerScale(9)} fill="blue" opacity=0.4></circle>
</svg>`}
Insert cell
Insert cell
import {Legend, Swatches} from "@d3/color-legend"
Insert cell
import { rewind } from "@fil/rewind"
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more