Why is the data not displayed proportionally here?
Averages:
Czech Republic ≈ Estonia
// countries in the order of the legend; areas within 10% of each other count as about equal// (radarAreaRatio is the area of Estonia divided by the area of the Czech Republic)htl.html`<ul><li>Areas:<br>Czech Republic ${radarAreaRatio <0.9?">": radarAreaRatio >1.1?"<":"≈"} Estonia</li></ul>`
// deck font and size (as the selection and the axis labels) instead of Plot's system-ui 10px,// and no bottom margin, so that it lines up with the selectionPlot.legend({color: radarColor,swatchSize:14,style: {fontSize:"14px",fontFamily:"inherit",marginBottom:0}})
// the order of the axes changes the areas, although the data stays the same// ↓ = axes sorted from highest to lowest value of that country (clockwise from the top)viewof radarOrder = Inputs.radio(["Czech Republic ↓","Mixed","Estonia ↓"], {value:"Czech Republic ↓"})
radarData =FileAttachment("data/competition_radar_2021.csv").csv({typed:true})radarPoints = radarData.flatMap(({name,...values}) =>Object.entries(values).map(([key, value]) => ({name, key, value})))// three predetermined orders of the axes: in the csv order (Czech Republic from highest to lowest)// the area of Estonia is about half of the area of the Czech Republic; in the mixed order both// areas are the same (areas of the drawn cardinal-closed curves; a random order gets within 10%// in about 3 of 10 cases)radarOrders = ({"Czech Republic ↓":Array.from(newSet(radarPoints.map(d => d.key))),"Mixed": ["At-risk-of-poverty rate","Multifactor productivity","Regional cohesion","Unemployment rate","Income distribution","Labor productivity","Employment rate","Share of renewable energy sources","Energy intensity","Current account balance","CO2 intensity","Economic output"],// Estonia from highest to lowest: now the area of the Czech Republic is about 70% of Estonia's"Estonia ↓": ["Multifactor productivity","Share of renewable energy sources","Employment rate","Regional cohesion","Unemployment rate","Economic output","Energy intensity","Labor productivity","Income distribution","Current account balance","At-risk-of-poverty rate","CO2 intensity"]})radarKeys = radarOrders[radarOrder]// the area connects the points in data order, so they have to follow the axes clockwiseradarPointsOrdered = d3.sort(radarPoints, d => radarKeys.indexOf(d.key))// distributes the axes onto longitudes, starting at 180 and winding back to one step before -180radarLongitude = d3.scalePoint(radarKeys, [180,-180]).padding(0.5).align(1)// area of a drawn outline: cardinal-closed curve (as in Plot.area) through the points at equal angles,// sampled and summed with the shoelace formula; radius = value, as in the projectionradarCurveArea = (values) => {const n = values.length, samples =20;const p = values.map((r, i) => [r *Math.cos(2*Math.PI* i / n), r *Math.sin(2*Math.PI* i / n)]);const at = (i) => p[(i + n) % n];let area =0, last = p[0];for (let i =0; i < n; i++) {const [p0, p1, p2, p3] = [at(i -1),at(i),at(i +1),at(i +2)];const c1 = [0,1].map(j => p1[j] + (p2[j] - p0[j]) /6);const c2 = [0,1].map(j => p2[j] - (p3[j] - p1[j]) /6);for (let k =1; k <= samples; k++) {const t = k / samples, u =1- t;const q = [0,1].map(j => u * u * u * p1[j] +3* u * u * t * c1[j] +3* u * t * t * c2[j] + t * t * t * p2[j]); area += last[0] * q[1] - q[0] * last[1]; last = q; } }returnMath.abs(area) /2;}radarAreaRatio = {const values = (name) => radarKeys.map(k => radarPoints.find(d => d.name=== name && d.key=== k).value);returnradarCurveArea(values("Estonia")) /radarCurveArea(values("Czech Republic"));}// wublue and craneorange of colors_wu from src/config.qmd (blue/orange stays distinguishable with// color vision deficiencies); the legend is drawn separately next to the selectionradarColor = ({domain: ["Czech Republic","Estonia"],range: ["#336699","#FCBB06"]})Plot.plot({width:550,// class to scope the hover css below to this chartclassName:"radar-chart",// transparent to match the slidestyle: {background:"transparent"},projection: {type:"azimuthal-equidistant",rotate: [0,-90],// 1.45° corresponds to the max. length (1) plus enough room for the labelsdomain: d3.geoCircle().center([0,90]).radius(1.45)() },color: radarColor,marks: [// grey discs Plot.geo([1,0.8,0.6,0.4,0.2], {geometry: (r) => d3.geoCircle().center([0,90]).radius(r)(),stroke:"black",fill:"black",strokeOpacity:0.3,fillOpacity:0.03,strokeWidth:0.5 }),// white axes Plot.link(radarLongitude.domain(), {x1: radarLongitude,y1:90-1.14,x2:0,y2:90,stroke:"white",strokeOpacity:0.5,strokeWidth:2.5 }),// tick labels// between the first two axes, so they do not collide with the top label Plot.text([0.6,0.8,1], {x:180-180/ radarKeys.length,y: (d) =>90- d,dx:2,textAnchor:"start",text: (d) =>`${Math.round(100* d)}%`,fill:"currentColor",stroke:"white",fontSize:8 }),// axes labels Plot.text(radarLongitude.domain(), {x: radarLongitude,y:90-1.22,text: Plot.identity,lineWidth:6,// style.scss sets all tspans (wrapped labels) to 14px, so single-line labels get the same sizefontSize:14 }),// areas Plot.area(radarPointsOrdered, {x1: ({key}) =>radarLongitude(key),y1: ({value}) =>90- value,x2:0,y2:90,fill:"name",stroke:"name",curve:"cardinal-closed" }),// points Plot.dot(radarPoints, {x: ({key}) =>radarLongitude(key),y: ({value}) =>90- value,fill:"name",stroke:"white" }),// interactive labels Plot.text(radarPoints, Plot.pointer({x: ({key}) =>radarLongitude(key),y: ({value}) =>90- value,text: (d) =>`${(100* d.value).toFixed(0)}%`,textAnchor:"start",dx:4,fill:"currentColor",stroke:"white",maxRadius:10 })),// interactive opacity on the areas; scoped with the class, since a style element in an svg// applies to the whole page (it changed the area on the Plot of Plots slide too) () => htl.svg`<style> .radar-chart g[aria-label=area] path {fill-opacity: 0.1; transition: fill-opacity .2s;} .radar-chart g[aria-label=area]:hover path:not(:hover) {fill-opacity: 0.05; transition: fill-opacity .2s;} .radar-chart g[aria-label=area] path:hover {fill-opacity: 0.3; transition: fill-opacity .2s;} </style>` ]})
Clear Labeling
“Clear labeling should be used to defeat graphical distortion and ambiguity.”
Show Data Variation
“Show data variation, not design variation.”
Quote in Context
“Graphics must not quote data out of context.”
No context
Time context
Time and country context
Interactive Contextualization
import { rangeSlider as tlRangeSlider } from"@mootari/range-slider"// arquero expressions refer to op by name, so it has to exist as a variableop = aq.optlDataUrl ="https://raw.githubusercontent.com/schmoigl/tariflohn-tracker/main/src/data/"tlTLI = d3.csv(tlDataUrl +"TLI.csv")tlPROD = d3.csv(tlDataUrl +"PROD.csv")tlVPI = d3.csv(tlDataUrl +"VPI.csv")// defaults of the notebook's inputstlIndices = ["Tariflohnindex","Verbraucherpreisindex"]tlSparte ="Insgesamt"tlSektor ="Gesamt (VGR-Daten; Alle Sektoren)"tlEinheit ="Produktivitätsindex je geleisteter Arbeitsstunde"tlProduktgruppe ="Gesamt"tlWidth =850tlHeight =380tlSliderWidth =700// colors_lecture from src/config.qmdtlColors = ["#336699",// Tariflohnindex"#2d8659",// Produktivitätsindex"#e52320",// Verbraucherpreisindex"#9C6B91",// Benyaindex"#d3d3d3",// Reallohnindex]tlConfig = ({view: { stroke:"transparent" },font:"Century Gothic",title: { fontSize:14,subtitleFontSize:13 },axis: { labelFontSize:12,titleFontSize:12,titleFontWeight:"normal" },legend: { labelFontSize:12,titleFontSize:12,titleFontWeight:"normal" },mark: { fontSize:12 },locale: {number: { decimal:",",thousands:".",grouping: [3] },time: {dateTime:"%A %e %B %Y, %X",date:"%d/%m/%Y",time:"%H:%M:%S",periods: ["AM","PM"],days: ["Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag","Sonntag"],shortDays: ["Mo","Di","Mi","Do","Fr","Sa","So"],months: ["Jänner","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],shortMonths: ["Jan","Feb","Mar","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"] } },background:"transparent"})// own locale instead of d3.timeFormatDefaultLocale, which would change d3 for the whole decktlFormatDate = {const locale =await d3.json("https://cdn.jsdelivr.net/npm/d3-time-format@4/locale/de-DE.json");return d3.timeFormatLocale(locale).format("%b %Y");}tlParseDate = d3.timeParse("%Y-%m-%d")tlMergeData = tlVPI.filter(e => e.Produktgruppe=== tlProduktgruppe).map(d => {const addTLI = tlTLI.filter(e => e.Sparte=== tlSparte).find(e => e.Monat=== d.Monat);const addPROD = tlPROD.filter(e => e.Sektor=== tlSektor).filter(e => e.Einheit=== tlEinheit).find(e => e.Monat=== d.Monat);return { ...d,...addTLI,...addPROD }; })tlStart =tlParseDate(tlMergeData[0].Monat)tlEnd =tlParseDate(tlMergeData[tlMergeData.length-1].Monat)// a function rather than the element itself: DOM declarations are displayed where they// are declared, so the slide creates the slider with viewof tlZeit = tlMakeSlider()tlMakeSlider = () => {const slider =tlRangeSlider({min:24,max: d3.timeMonth.count(tlStart, tlEnd),step:1,format: d =>tlFormatDate(d3.timeMonth.offset(tlStart, d)),value: [155,169],separator:" → ",color:"#336699", }); slider.querySelector(".range-slider").style.width= tlSliderWidth +"px";return slider;}tlStartIndexDate =tlFormatDate(tlParseDate(tlMergeData[tlZeit[0]].Monat))// index rebased to the first month of the chosen period ("Rollierend" in the notebook)tlIndexData = aq.from(tlMergeData).derive({Verbraucherpreisindex: d =>+ d.Verbraucherpreisindex,Tariflohnindex: d =>+ d.Tariflohnindex, }).derive({ row: d => op.row_number() }).filter(aq.escape(d => d.row>= tlZeit[0] +1&& d.row<= tlZeit[1])).derive({Verbraucherpreisindex: d => d.Verbraucherpreisindex/ op.first_value(d.Verbraucherpreisindex) *100,Tariflohnindex: d => d.Tariflohnindex/ op.first_value(d.Tariflohnindex) *100, }).select(tlIndices.concat("Monat")).fold(tlIndices).filter(aq.escape(d =>!isNaN(d.value)))tlColorScale = ({domain: ["Tariflohnindex","Produktivitätsindex","Verbraucherpreisindex","Benyaindex","Reallohnindex"],range: tlColors})tlLines = vl.markLine({ point: { fill:"transparent",size:200 } }).encode( vl.x().fieldT("Monat").axis({title:null,format:"%b %y",minExtent:40,grid:false,labelAngle:0,labelPadding:10,labelOverlap:true,labelBound:true,labelSeparation:5, }), vl.y().fieldQ("value").axis({title:null,domain:false,minExtent:40,ticks:false,labelPadding:10,labelOverlap:true,labelBound:true,labelSeparation:5,format:",.0f",grid:false, }).scale({ zero:false,nice:false }), vl.color().fieldN("key").legend({ orient:"top-left",symbolType:"stroke",title:null,symbolSize:200,values: tlIndices }).scale(tlColorScale), vl.tooltip([ { field:"key",title:"Index" }, { field:"value",title:"Indexwert",format:",.1f" }, { field:"Monat",title:"Monat",type:"temporal",format:"%b %y" } ]), )// growth over the period, labelled at the last point of each linetlLabels = vl.markText({ xOffset:30,fontSize:15 }).transform( vl.window(vl.row_number().as("row")), vl.joinaggregate({ op:"max",field:"row",as:"max" }).groupby("key"), vl.filter("datum.row == datum.max"), vl.calculate("(datum.value - 100) / 100").as("value2"), ).encode( vl.x().fieldT("Monat"), vl.y().fieldQ("value"), vl.text().fieldQ("value2").format("+,.1%"), vl.color().fieldN("key").scale(tlColorScale), )tlRuleHundred = vl.markRule({ strokeWidth:1 }).transform(vl.calculate("100").as("hundred")).encode(vl.y().fieldQ("hundred"))// rendered on the slide with tariflohnSpec.render()tariflohnSpec = vl.layer(tlLines, tlLabels, tlRuleHundred).data(tlIndexData.objects()).width(tlWidth).height(tlHeight).autosize({ type:"fit",contains:"padding" }).title({text:"Index",subtitle: tlStartIndexDate +" = 100",align:"left",anchor:"start", }).config(tlConfig)
Let the user choose time context
tariflohnSpec.render({ renderer:"svg" })
viewof tlZeit =tlMakeSlider()
Creating Ducks
“It is all right to decorate construction but never construct decoration”
Mobilization of Elements
“Mobilize every graphical element, perhaps several times over, to show the data!”
Legend is
color guide
histogram
range selection
unit selection
Scaling based on
viewof button = Inputs.button([ ["quantile", value =>"quantile"], ["absolute", value =>"linear"], ], {label:null,value:"quantile"})// viewof button2 = Inputs.button([// ["in Euro", value => "in Euro"],// ["Euro pro Nutzfläche", value => "Euro pro Nutzfläche"]// ],// {label: null, value: "in Euro"})button2 ="in Euro"
// Vega 5 (used by vl) ignores reveal's scaling of the slides when it maps the mouse onto the// chart, so the range selection lands too far right on large screens; Vega 6 accounts for it{const [vega6, vegaLite6, vegaTooltip] =awaitPromise.all([import("https://cdn.jsdelivr.net/npm/vega@6.4.0/+esm"),import("https://cdn.jsdelivr.net/npm/vega-lite@6/+esm"),import("https://cdn.jsdelivr.net/npm/vega-tooltip@1/+esm") ]);const container =document.createElement("div");const view =new vega6.View(vega6.parse(vegaLite6.compile(viewHangingHistogram.toSpec()).spec), { container,renderer:"svg",hover:true,tooltip:new vegaTooltip.Handler().call });await view.runAsync(); invalidation.then(() => view.finalize());// the chart arrives after reveal has centered the slide, so center it again once it is shownsetTimeout(() =>window.Reveal?.layout(),0);return container;}
Technological Phallacy
“Occasionally designers seem to seek credit merely for possessing a new technology, rather than using it to make better designs”
import {addExtendedProjections, addProjections, extendedProjections} from'@vega/vega-utilities'import {checkbox, menu, rotate3D, slider, translate2D} from'@jheer/dom-utilities'vlExtended = {awaitaddExtendedProjections(vl.vega);// d3-geo-projection does not clip at the cuts of interrupted projections, so graticules// and shapes are drawn across the gaps; d3-geo-polygon has clipped versions of themaddProjections(vl.vega,awaitrequire('d3-geo-polygon@2'), ['berghaus','gingery','healpix','interruptedHomolosine','interruptedSinusoidal','interruptedBoggs','interruptedSinuMollweide','interruptedMollweide','interruptedMollweideHemispheres','polyhedralButterfly','polyhedralCollignon','polyhedralWaterman','twoPointEquidistantUsa' ]);return vl;}projections = ['naturalEarth1','albers','azimuthalEqualArea','azimuthalEquidistant','conicConformal','conicEqualArea','conicEquidistant','equirectangular','gnomonic','mercator','orthographic','stereographic','transverseMercator',...extendedProjections]map = vl.layer( vl.markGeoshape({fill:'#e6f3ff'}).data(vl.sphere()), vl.markGeoshape({stroke:'#ffffff',strokeWidth:1}).data(vl.graticule()), vl.markGeoshape({fill:'#d3d3d3',stroke:'#706545',strokeWidth:0.5}).data(vl.topojson(world).feature('countries')),// Tissot's indicatrix: identical small circles on the globe, drawn on top when toggled on vl.markGeoshape({fill:'#e52320',fillOpacity:0.6,stroke:'#e52320',strokeWidth:0.5,opacity: {expr:'tissot ? 1 : 0'}}).data({values: {type:'FeatureCollection',features: tissotCircles},format: {type:'json',property:'features'}}) ).width(900).height(500).config({view: {stroke:null}})tissotCircles = d3.range(-165,180,30).flatMap(lon => d3.range(-75,76,25).map(lat => ({type:'Feature',geometry: d3.geoCircle().center([lon, lat]).radius(4)() })))type =menu('Type', projections)scale =slider('Scale',140,50,1000,1)tissot =checkbox("Tissot's indicatrix",false)