From 447a537ceca3a746cef36e1a261bbc47020d17f9 Mon Sep 17 00:00:00 2001 From: holtzy Date: Tue, 2 Apr 2024 09:26:25 +0000 Subject: [PATCH] =?UTF-8?q?Deploying=20to=20gh-pages=20from=20@=20holtzy/r?= =?UTF-8?q?eact-graph-gallery@139163256bffa753f5d5a221233c639e896fd7ca=20?= =?UTF-8?q?=F0=9F=9A=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 2d-density-plot.html | 4 +- 404.html | 2 +- .../_buildManifest.js | 2 +- .../_ssgManifest.js | 0 ...40a8.js => timeseries-f4bc20799e7f6303.js} | 2 +- about.html | 2 +- add-hover-interaction-to-graph.html | 4 +- all.html | 2 +- animation.html | 2 +- arc-diagram.html | 4 +- area-plot.html | 4 +- articles.html | 2 +- barplot.html | 4 +- boxplot.html | 4 +- bubble-map.html | 4 +- bubble-plot.html | 4 +- build-axis-with-react.html | 4 +- cartogram.html | 2 +- chord-diagram.html | 4 +- choropleth-map.html | 4 +- circular-barplot.html | 4 +- circular-packing.html | 4 +- connected-scatter-plot.html | 4 +- connection-map.html | 4 +- correlogram.html | 4 +- cross-graph-highlight-interaction.html | 4 +- dataset-transition.html | 4 +- dendrogram.html | 4 +- density-plot.html | 4 +- donut.html | 4 +- example/arc-diagram-vertical.html | 4 +- .../barplot-data-transition-animation.html | 4 +- example/barplot-stacked-horizontal.html | 4 +- example/barplot-stacked-vertical.html | 2 +- example/boxplot-horizontal.html | 4 +- example/boxplot-jitter.html | 4 +- example/circle-packing-with-d3-force.html | 4 +- example/histogram-mirror.html | 4 +- example/histogram-small-multiple.html | 4 +- example/histogram-with-several-groups.html | 4 +- example/line-chart-synchronized-cursors.html | 4 +- .../network-diagram-with-colored-groups.html | 4 +- example/radar-chart-animation.html | 4 +- example/scatterplot-basic-canvas.html | 4 +- ...h-voronoi-for-closest-point-detection.html | 4 +- example/timeseries-moving-average.html | 4 +- fix-canvas-blurry-dataviz.html | 2 +- heatmap.html | 8 +- hexbin-map.html | 4 +- hierarchical-edge-bundling.html | 4 +- histogram.html | 6 +- index.html | 2 +- interactivity.html | 2 +- line-chart.html | 4 +- lollipop-plot.html | 4 +- make-a-graph-responsive.html | 4 +- map.html | 4 +- network-chart.html | 4 +- parallel-plot.html | 4 +- pie-plot.html | 4 +- radar-chart.html | 4 +- ...t-dataviz-animation-with-react-spring.html | 2 +- ridgeline.html | 4 +- sankey-diagram.html | 4 +- scatter-plot.html | 4 +- shape-morphism-for-dataviz-with-react.html | 4 +- sitemap.xml | 148 +++++++++--------- stacked-area-plot.html | 4 +- stacked-barplot-with-negative-values.html | 2 +- streamchart.html | 4 +- subscribe.html | 2 +- timeseries.html | 4 +- treemap.html | 4 +- typescript-d3-axis.html | 4 +- violin-plot.html | 4 +- viz-from-the-future.html | 2 +- voronoi.html | 4 +- what-is-a-color.html | 2 +- wordcloud.html | 4 +- 79 files changed, 214 insertions(+), 214 deletions(-) rename _next/static/{Tom4mSBFXG8ojMuGCMlo3 => 0bXDBMA-wxGoxt3q0CCX7}/_buildManifest.js (99%) rename _next/static/{Tom4mSBFXG8ojMuGCMlo3 => 0bXDBMA-wxGoxt3q0CCX7}/_ssgManifest.js (100%) rename _next/static/chunks/pages/{timeseries-fdae5d855aa440a8.js => timeseries-f4bc20799e7f6303.js} (63%) diff --git a/2d-density-plot.html b/2d-density-plot.html index 1fc26981..5c73d513 100644 --- a/2d-density-plot.html +++ b/2d-density-plot.html @@ -1,4 +1,4 @@ -How to build a 2d density chart with React and D3.

2d density chart

Dataviz logo representing a 2dDensity chart.

A 2D density chart is a graphical representation of data that uses color to show the concentration of data points in a given area. It shows the combined distribution of two quantitative variables. 2D density charts are often used in statistical analysis and data mining to identify trends, patterns, and correlations in the data.

In this tutorial, we will use the d3.js and React libraries to build a 2D density chart. It starts by describing how the data should be organized and how to initialize the Density2d component. It then explains how to prepare the data and compute bins. Once this is done, it shows how to render the shapes and suggests a few variations. πŸ™‡β€β™‚οΈ.

Useful links

The Data

A 2d density chart is basically a variation of the scatterplot, useful when the amount of data points is huge. As a result, it shares the same data structure.

The data is an array of object. For each object, at least 2 properties are required: x and y. The value of x is the position of the datapoint on the horizontal axis. The value of y is linked with the vertical axis.

const data = [
+How to build a 2d density chart with React and D3.

2d density chart

Dataviz logo representing a 2dDensity chart.

A 2D density chart is a graphical representation of data that uses color to show the concentration of data points in a given area. It shows the combined distribution of two quantitative variables. 2D density charts are often used in statistical analysis and data mining to identify trends, patterns, and correlations in the data.

In this tutorial, we will use the d3.js and React libraries to build a 2D density chart. It starts by describing how the data should be organized and how to initialize the Density2d component. It then explains how to prepare the data and compute bins. Once this is done, it shows how to render the shapes and suggests a few variations. πŸ™‡β€β™‚οΈ.

Useful links

The Data

A 2d density chart is basically a variation of the scatterplot, useful when the amount of data points is huge. As a result, it shares the same data structure.

The data is an array of object. For each object, at least 2 properties are required: x and y. The value of x is the position of the datapoint on the horizontal axis. The value of y is linked with the vertical axis.

const data = [
   {
     x: 2,
     y: 4
@@ -75,4 +75,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




2D Density inspiration

If you're looking for inspiration to create your next 2D Density, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your 2D Density looks good!

visit

Variations

The hexbin representation above is just one member of a family of graphics allowing to study the combined distribution of two quantitative variables. You can read more about the existing variations in the data to viz project.

To put it in a nutshell, 2d histogram, Gaussian KDE, 2d density and Contour charts are the most common variations. It is of course possible to build them all using react and d3.js.

Here is an example with a contounr chart based on the same dataset than the previous example.


5101520

Contour chart made with React and D3.js.

ToDomake the contour chart above looks better
ToDoadd examples for 2d histograms and other variations
ToDoAdd example with a zoom feature implemented

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




2D Density inspiration

If you're looking for inspiration to create your next 2D Density, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your 2D Density looks good!

visit

Variations

The hexbin representation above is just one member of a family of graphics allowing to study the combined distribution of two quantitative variables. You can read more about the existing variations in the data to viz project.

To put it in a nutshell, 2d histogram, Gaussian KDE, 2d density and Contour charts are the most common variations. It is of course possible to build them all using react and d3.js.

Here is an example with a contounr chart based on the same dataset than the previous example.


5101520

Contour chart made with React and D3.js.

ToDomake the contour chart above looks better
ToDoadd examples for 2d histograms and other variations
ToDoAdd example with a zoom feature implemented

Correlation

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/404.html b/404.html index 1f12ec7e..57f0a15a 100644 --- a/404.html +++ b/404.html @@ -1 +1 @@ -How to build a scatter plot with React and D3.

Oh No!

Dataviz logo representing a ScatterPlot chart.

It looks like the place you are looking for does not exist πŸ™ˆ

You probably want to go back to the gallery homepage!

I'm in a good mood, so here is a chart example for you just in case you are interested in React and d3.js β˜€οΈ

Useful links

The countries with the highest vulnerability to climate change have the lowest CO2 emissions

All countries sorted by their vulnerability and readiness to climate change. The size shows the CO2 emission per person in that country.

High Readiness↑Low Readiness↓QatarBahrainU.S.Trinidad and TobagoCzech RepublicSingaporeNorwayIndiaSudanChadSomalia

Reproduction of a chart originally published by Data Wrapper using react and d3.js.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +How to build a scatter plot with React and D3.

Oh No!

Dataviz logo representing a ScatterPlot chart.

It looks like the place you are looking for does not exist πŸ™ˆ

You probably want to go back to the gallery homepage!

I'm in a good mood, so here is a chart example for you just in case you are interested in React and d3.js β˜€οΈ

Useful links

The countries with the highest vulnerability to climate change have the lowest CO2 emissions

All countries sorted by their vulnerability and readiness to climate change. The size shows the CO2 emission per person in that country.

High Readiness↑Low Readiness↓QatarBahrainU.S.Trinidad and TobagoCzech RepublicSingaporeNorwayIndiaSudanChadSomalia

Reproduction of a chart originally published by Data Wrapper using react and d3.js.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/_next/static/Tom4mSBFXG8ojMuGCMlo3/_buildManifest.js b/_next/static/0bXDBMA-wxGoxt3q0CCX7/_buildManifest.js similarity index 99% rename from _next/static/Tom4mSBFXG8ojMuGCMlo3/_buildManifest.js rename to _next/static/0bXDBMA-wxGoxt3q0CCX7/_buildManifest.js index 64a4235d..e542f3e9 100644 --- a/_next/static/Tom4mSBFXG8ojMuGCMlo3/_buildManifest.js +++ b/_next/static/0bXDBMA-wxGoxt3q0CCX7/_buildManifest.js @@ -1 +1 @@ -self.__BUILD_MANIFEST=function(a,s,t,e,c,i,r,o,p,n,l,d,h,b,g,u,m,f,k){return{__rewrites:{beforeFiles:[],afterFiles:[],fallback:[]},"/":[a,"static/chunks/2718-9db1e423a693cb66.js",s,"static/chunks/pages/index-02f1611bbdcd8a7f.js"],"/2d-density-plot":[a,t,e,s,i,c,"static/chunks/pages/2d-density-plot-9dfdc48c92e54f42.js"],"/404":[a,t,s,d,"static/css/a49219f4d8c3ed5a.css","static/chunks/pages/404-b59b4ff388de3e75.js"],"/_error":["static/chunks/pages/_error-bd1da5a6907513b5.js"],"/about":[a,t,s,c,"static/chunks/pages/about-27a3b8eb6520f153.js"],"/add-hover-interaction-to-graph":[a,t,e,s,b,g,"static/css/fe46d86521d3aec0.css","static/chunks/pages/add-hover-interaction-to-graph-deac98a87660e979.js"],"/all":[a,s,r,p,"static/chunks/pages/all-a45a86b09df3af16.js"],"/animation":[a,s,r,p,"static/chunks/pages/animation-af731f2c2f3d37de.js"],"/arc-diagram":[a,t,e,s,i,r,p,"static/chunks/pages/arc-diagram-a79a146b98512a5f.js"],"/area-plot":[a,t,e,s,c,"static/chunks/pages/area-plot-0f8bf30a981896e7.js"],"/articles":[a,s,c,"static/chunks/pages/articles-d68532e1c3366d69.js"],"/barplot":[a,t,e,o,s,i,r,p,"static/chunks/pages/barplot-54f288df0951e3e5.js"],"/boxplot":[a,t,e,s,i,r,p,"static/chunks/pages/boxplot-bc741002fbbae838.js"],"/bubble-map":[a,t,e,o,s,i,r,l,p,"static/chunks/pages/bubble-map-f0510f13b57f0c76.js"],"/bubble-plot":[a,t,e,o,s,i,r,d,"static/css/8111ac3faa96fda6.css","static/chunks/pages/bubble-plot-829fe977bc19647e.js"],"/build-axis-with-react":[a,t,e,s,h,c,"static/chunks/pages/build-axis-with-react-89108a6ad19d43e7.js"],"/cartogram":[a,s,c,"static/chunks/pages/cartogram-64b6e3ba6f269212.js"],"/chord-diagram":[a,t,e,s,i,c,"static/chunks/pages/chord-diagram-a1c455b2ddaccb45.js"],"/choropleth-map":[a,t,e,s,i,l,c,"static/chunks/pages/choropleth-map-9650a530fe2650b9.js"],"/circular-barplot":[a,t,e,s,c,"static/chunks/pages/circular-barplot-c6596e900c19d521.js"],"/circular-packing":[a,t,e,o,s,r,p,"static/chunks/pages/circular-packing-e36944c4a5107f9f.js"],"/connected-scatter-plot":[a,t,e,s,i,c,"static/chunks/pages/connected-scatter-plot-3f4841b9bbcc42bf.js"],"/connection-map":[a,t,e,s,i,l,c,"static/chunks/pages/connection-map-4435ef08ea9150c6.js"],"/correlogram":[a,t,e,s,"static/css/cea17a168dacc574.css","static/chunks/pages/correlogram-e797a35f07ab0146.js"],"/cross-graph-highlight-interaction":[a,t,e,"static/chunks/8446-9e00e6d08370f23e.js",s,"static/css/fc088fa6e640432a.css","static/chunks/pages/cross-graph-highlight-interaction-6cdbc8d6ad443b5c.js"],"/dataset-transition":[a,t,e,o,s,c,"static/chunks/pages/dataset-transition-fdc2801d5e288631.js"],"/dendrogram":[a,t,e,s,i,c,"static/chunks/pages/dendrogram-6ff36cbb9af33f65.js"],"/density-plot":[a,t,e,s,i,u,c,"static/chunks/pages/density-plot-1ecbe7950483848d.js"],"/donut":[a,t,e,o,n,s,i,"static/css/87771490cc5a8694.css","static/chunks/pages/donut-24bef9439f677cd2.js"],"/example/arc-diagram-vertical":[a,t,e,s,c,"static/chunks/pages/example/arc-diagram-vertical-1947c029bebad520.js"],"/example/barplot-data-transition-animation":[a,t,e,o,s,c,"static/chunks/pages/example/barplot-data-transition-animation-758a398c0bcf9834.js"],"/example/barplot-stacked-horizontal":[a,t,e,s,r,p,"static/chunks/pages/example/barplot-stacked-horizontal-67094d35533800a9.js"],"/example/barplot-stacked-vertical":[a,t,s,r,m,p,"static/chunks/pages/example/barplot-stacked-vertical-b76af27326ae0122.js"],"/example/boxplot-horizontal":[a,t,e,s,c,"static/chunks/pages/example/boxplot-horizontal-73d7ed91c93aa78f.js"],"/example/boxplot-jitter":[a,t,e,s,c,"static/chunks/pages/example/boxplot-jitter-92d73a27ab193815.js"],"/example/circle-packing-with-d3-force":[a,t,e,s,c,"static/chunks/pages/example/circle-packing-with-d3-force-191596afcad226e0.js"],"/example/histogram-mirror":[a,t,e,s,c,"static/chunks/pages/example/histogram-mirror-82c696df1d198c66.js"],"/example/histogram-small-multiple":[a,t,e,s,c,"static/chunks/pages/example/histogram-small-multiple-040b1340eb4781bf.js"],"/example/histogram-with-several-groups":[a,t,e,s,c,"static/chunks/pages/example/histogram-with-several-groups-866eefb4c7cb8a27.js"],"/example/line-chart-synchronized-cursors":[a,t,e,o,s,c,"static/chunks/pages/example/line-chart-synchronized-cursors-45455b1b48d87ec0.js"],"/example/network-diagram-with-colored-groups":[a,t,e,s,c,"static/chunks/pages/example/network-diagram-with-colored-groups-4dd07ea51653d25e.js"],"/example/radar-chart-animation":[a,t,e,o,s,c,"static/chunks/pages/example/radar-chart-animation-26d804b0ca7306b3.js"],"/example/scatterplot-basic-canvas":[a,t,e,s,c,"static/chunks/pages/example/scatterplot-basic-canvas-c9069cc0bd326568.js"],"/example/scatterplot-tooltip-with-voronoi-for-closest-point-detection":[a,t,e,s,c,"static/chunks/pages/example/scatterplot-tooltip-with-voronoi-for-closest-point-detection-5a9a4215dc2f540f.js"],"/example/timeseries-moving-average":[a,t,e,s,r,"static/css/737f297697af8e75.css","static/chunks/pages/example/timeseries-moving-average-2461b9f5b0b20187.js"],"/fix-canvas-blurry-dataviz":[a,e,s,c,"static/chunks/pages/fix-canvas-blurry-dataviz-0f5665f678d67150.js"],"/heatmap":[a,t,e,s,i,"static/css/54771664905458da.css","static/chunks/pages/heatmap-71e07ca47a37103d.js"],"/hexbin-map":[a,t,e,s,i,c,"static/chunks/pages/hexbin-map-99453d28d36c6e74.js"],"/hierarchical-edge-bundling":[a,t,e,s,c,"static/chunks/pages/hierarchical-edge-bundling-fd6ca94961617e9c.js"],"/histogram":[a,t,e,o,s,i,r,p,"static/chunks/pages/histogram-e5200c648df817c5.js"],"/interactivity":[a,s,r,p,"static/chunks/pages/interactivity-7ca43c0c19947970.js"],"/line-chart":[a,t,e,o,s,i,r,p,"static/chunks/pages/line-chart-927189a8e9d2121c.js"],"/lollipop-plot":[a,t,e,o,s,i,r,"static/css/46c836e7a496aab6.css","static/chunks/pages/lollipop-plot-9b5c40befee60b29.js"],"/make-a-graph-responsive":[a,t,e,s,f,c,"static/chunks/pages/make-a-graph-responsive-54c7d37bac687a18.js"],"/map":[a,t,e,s,i,l,c,"static/chunks/pages/map-3cb1576844fe5161.js"],"/network-chart":[a,t,e,s,i,r,p,"static/chunks/pages/network-chart-b51ddd38466bd38d.js"],"/parallel-plot":[a,t,e,s,i,c,"static/chunks/pages/parallel-plot-e5d68ff4cd0d93e9.js"],"/pie-plot":[a,t,e,o,n,s,i,"static/css/2d55ec714184f95f.css","static/chunks/pages/pie-plot-627de5fc53195805.js"],"/radar-chart":[a,t,e,s,i,r,p,"static/chunks/pages/radar-chart-2275cd8c825f7675.js"],"/react-dataviz-animation-with-react-spring":[a,t,o,s,h,c,"static/chunks/pages/react-dataviz-animation-with-react-spring-443223440d38c735.js"],"/ridgeline":[a,t,e,s,i,r,u,p,"static/chunks/pages/ridgeline-449dd144bca04678.js"],"/sankey-diagram":[a,t,e,s,i,c,"static/chunks/pages/sankey-diagram-19a97dc46872907b.js"],"/scatter-plot":[a,t,e,s,i,r,d,b,"static/css/270731084cbdc85c.css","static/chunks/pages/scatter-plot-1c291c54c67f56ca.js"],"/shape-morphism-for-dataviz-with-react":[a,t,e,o,n,s,h,c,"static/chunks/pages/shape-morphism-for-dataviz-with-react-0ebc0c09a2e850bd.js"],"/stacked-area-plot":[a,t,e,o,n,s,i,k,"static/css/6a457c10c5ce26af.css","static/chunks/pages/stacked-area-plot-88f1f0e8e047d5bf.js"],"/stacked-barplot-with-negative-values":[a,t,s,m,c,"static/chunks/pages/stacked-barplot-with-negative-values-aa855da28d12c3bc.js"],"/streamchart":[a,t,e,o,n,s,i,k,"static/css/2b88bb4356e37def.css","static/chunks/pages/streamchart-efa36dd7f75cffba.js"],"/subscribe":[a,s,c,"static/chunks/pages/subscribe-252d98ebd6c86e52.js"],"/timeseries":[a,t,e,o,s,i,r,p,"static/chunks/pages/timeseries-fdae5d855aa440a8.js"],"/treemap":[a,t,e,s,g,"static/css/541a348b4668d195.css","static/chunks/pages/treemap-07098dcfa250908c.js"],"/typescript-d3-axis":[a,t,e,s,c,"static/chunks/pages/typescript-d3-axis-4c3b81bd97d47528.js"],"/violin-plot":[a,t,e,s,i,f,c,"static/chunks/pages/violin-plot-b2a3ec093b945883.js"],"/viz-from-the-future":[a,s,"static/css/b340902f13331342.css","static/chunks/pages/viz-from-the-future-5a5f6687159543a9.js"],"/voronoi":[a,t,e,s,i,r,p,"static/chunks/pages/voronoi-501b16cecc4add01.js"],"/what-is-a-color":[a,s,c,"static/chunks/pages/what-is-a-color-bd202c908100f7b1.js"],"/wordcloud":[a,t,e,s,c,"static/chunks/pages/wordcloud-5b4a401f67f7ddb4.js"],sortedPages:["/","/2d-density-plot","/404","/_app","/_error","/about","/add-hover-interaction-to-graph","/all","/animation","/arc-diagram","/area-plot","/articles","/barplot","/boxplot","/bubble-map","/bubble-plot","/build-axis-with-react","/cartogram","/chord-diagram","/choropleth-map","/circular-barplot","/circular-packing","/connected-scatter-plot","/connection-map","/correlogram","/cross-graph-highlight-interaction","/dataset-transition","/dendrogram","/density-plot","/donut","/example/arc-diagram-vertical","/example/barplot-data-transition-animation","/example/barplot-stacked-horizontal","/example/barplot-stacked-vertical","/example/boxplot-horizontal","/example/boxplot-jitter","/example/circle-packing-with-d3-force","/example/histogram-mirror","/example/histogram-small-multiple","/example/histogram-with-several-groups","/example/line-chart-synchronized-cursors","/example/network-diagram-with-colored-groups","/example/radar-chart-animation","/example/scatterplot-basic-canvas","/example/scatterplot-tooltip-with-voronoi-for-closest-point-detection","/example/timeseries-moving-average","/fix-canvas-blurry-dataviz","/heatmap","/hexbin-map","/hierarchical-edge-bundling","/histogram","/interactivity","/line-chart","/lollipop-plot","/make-a-graph-responsive","/map","/network-chart","/parallel-plot","/pie-plot","/radar-chart","/react-dataviz-animation-with-react-spring","/ridgeline","/sankey-diagram","/scatter-plot","/shape-morphism-for-dataviz-with-react","/stacked-area-plot","/stacked-barplot-with-negative-values","/streamchart","/subscribe","/timeseries","/treemap","/typescript-d3-axis","/violin-plot","/viz-from-the-future","/voronoi","/what-is-a-color","/wordcloud"]}}("static/chunks/3996-a4c96d7d78feb6f0.js","static/chunks/645-4872c822908c5080.js","static/chunks/7875-aadd425170e96677.js","static/chunks/5660-b8db8bc796807373.js","static/css/2247407c30b587b7.css","static/chunks/298-262f4755eac029e8.js","static/chunks/693-4a5fc90e80b9912a.js","static/chunks/2236-8bd9f36cdf4ac8bf.js","static/css/537902226fc25775.css","static/chunks/7303-913c346170e452f6.js","static/chunks/9421-5e6efef247940edd.js","static/chunks/2428-596304aec42c5d97.js","static/chunks/9142-8b575f64a3911647.js","static/chunks/5058-9d24a7b31eaedf24.js","static/chunks/8548-01181bf23ffbcfb5.js","static/chunks/8986-848154b8dc14ec20.js","static/chunks/7436-22099e6b70eb9b18.js","static/chunks/7022-dca9915a908fa916.js","static/chunks/3555-27c193c666fc06d4.js"),self.__BUILD_MANIFEST_CB&&self.__BUILD_MANIFEST_CB(); \ No newline at end of file +self.__BUILD_MANIFEST=function(a,s,t,e,c,i,r,o,p,n,l,d,h,b,g,u,m,f,k){return{__rewrites:{beforeFiles:[],afterFiles:[],fallback:[]},"/":[a,"static/chunks/2718-9db1e423a693cb66.js",s,"static/chunks/pages/index-02f1611bbdcd8a7f.js"],"/2d-density-plot":[a,t,e,s,i,c,"static/chunks/pages/2d-density-plot-9dfdc48c92e54f42.js"],"/404":[a,t,s,d,"static/css/a49219f4d8c3ed5a.css","static/chunks/pages/404-b59b4ff388de3e75.js"],"/_error":["static/chunks/pages/_error-bd1da5a6907513b5.js"],"/about":[a,t,s,c,"static/chunks/pages/about-27a3b8eb6520f153.js"],"/add-hover-interaction-to-graph":[a,t,e,s,b,g,"static/css/fe46d86521d3aec0.css","static/chunks/pages/add-hover-interaction-to-graph-deac98a87660e979.js"],"/all":[a,s,r,p,"static/chunks/pages/all-a45a86b09df3af16.js"],"/animation":[a,s,r,p,"static/chunks/pages/animation-af731f2c2f3d37de.js"],"/arc-diagram":[a,t,e,s,i,r,p,"static/chunks/pages/arc-diagram-a79a146b98512a5f.js"],"/area-plot":[a,t,e,s,c,"static/chunks/pages/area-plot-0f8bf30a981896e7.js"],"/articles":[a,s,c,"static/chunks/pages/articles-d68532e1c3366d69.js"],"/barplot":[a,t,e,o,s,i,r,p,"static/chunks/pages/barplot-54f288df0951e3e5.js"],"/boxplot":[a,t,e,s,i,r,p,"static/chunks/pages/boxplot-bc741002fbbae838.js"],"/bubble-map":[a,t,e,o,s,i,r,l,p,"static/chunks/pages/bubble-map-f0510f13b57f0c76.js"],"/bubble-plot":[a,t,e,o,s,i,r,d,"static/css/8111ac3faa96fda6.css","static/chunks/pages/bubble-plot-829fe977bc19647e.js"],"/build-axis-with-react":[a,t,e,s,h,c,"static/chunks/pages/build-axis-with-react-89108a6ad19d43e7.js"],"/cartogram":[a,s,c,"static/chunks/pages/cartogram-64b6e3ba6f269212.js"],"/chord-diagram":[a,t,e,s,i,c,"static/chunks/pages/chord-diagram-a1c455b2ddaccb45.js"],"/choropleth-map":[a,t,e,s,i,l,c,"static/chunks/pages/choropleth-map-9650a530fe2650b9.js"],"/circular-barplot":[a,t,e,s,c,"static/chunks/pages/circular-barplot-c6596e900c19d521.js"],"/circular-packing":[a,t,e,o,s,r,p,"static/chunks/pages/circular-packing-e36944c4a5107f9f.js"],"/connected-scatter-plot":[a,t,e,s,i,c,"static/chunks/pages/connected-scatter-plot-3f4841b9bbcc42bf.js"],"/connection-map":[a,t,e,s,i,l,c,"static/chunks/pages/connection-map-4435ef08ea9150c6.js"],"/correlogram":[a,t,e,s,"static/css/cea17a168dacc574.css","static/chunks/pages/correlogram-e797a35f07ab0146.js"],"/cross-graph-highlight-interaction":[a,t,e,"static/chunks/8446-9e00e6d08370f23e.js",s,"static/css/fc088fa6e640432a.css","static/chunks/pages/cross-graph-highlight-interaction-6cdbc8d6ad443b5c.js"],"/dataset-transition":[a,t,e,o,s,c,"static/chunks/pages/dataset-transition-fdc2801d5e288631.js"],"/dendrogram":[a,t,e,s,i,c,"static/chunks/pages/dendrogram-6ff36cbb9af33f65.js"],"/density-plot":[a,t,e,s,i,u,c,"static/chunks/pages/density-plot-1ecbe7950483848d.js"],"/donut":[a,t,e,o,n,s,i,"static/css/87771490cc5a8694.css","static/chunks/pages/donut-24bef9439f677cd2.js"],"/example/arc-diagram-vertical":[a,t,e,s,c,"static/chunks/pages/example/arc-diagram-vertical-1947c029bebad520.js"],"/example/barplot-data-transition-animation":[a,t,e,o,s,c,"static/chunks/pages/example/barplot-data-transition-animation-758a398c0bcf9834.js"],"/example/barplot-stacked-horizontal":[a,t,e,s,r,p,"static/chunks/pages/example/barplot-stacked-horizontal-67094d35533800a9.js"],"/example/barplot-stacked-vertical":[a,t,s,r,m,p,"static/chunks/pages/example/barplot-stacked-vertical-b76af27326ae0122.js"],"/example/boxplot-horizontal":[a,t,e,s,c,"static/chunks/pages/example/boxplot-horizontal-73d7ed91c93aa78f.js"],"/example/boxplot-jitter":[a,t,e,s,c,"static/chunks/pages/example/boxplot-jitter-92d73a27ab193815.js"],"/example/circle-packing-with-d3-force":[a,t,e,s,c,"static/chunks/pages/example/circle-packing-with-d3-force-191596afcad226e0.js"],"/example/histogram-mirror":[a,t,e,s,c,"static/chunks/pages/example/histogram-mirror-82c696df1d198c66.js"],"/example/histogram-small-multiple":[a,t,e,s,c,"static/chunks/pages/example/histogram-small-multiple-040b1340eb4781bf.js"],"/example/histogram-with-several-groups":[a,t,e,s,c,"static/chunks/pages/example/histogram-with-several-groups-866eefb4c7cb8a27.js"],"/example/line-chart-synchronized-cursors":[a,t,e,o,s,c,"static/chunks/pages/example/line-chart-synchronized-cursors-45455b1b48d87ec0.js"],"/example/network-diagram-with-colored-groups":[a,t,e,s,c,"static/chunks/pages/example/network-diagram-with-colored-groups-4dd07ea51653d25e.js"],"/example/radar-chart-animation":[a,t,e,o,s,c,"static/chunks/pages/example/radar-chart-animation-26d804b0ca7306b3.js"],"/example/scatterplot-basic-canvas":[a,t,e,s,c,"static/chunks/pages/example/scatterplot-basic-canvas-c9069cc0bd326568.js"],"/example/scatterplot-tooltip-with-voronoi-for-closest-point-detection":[a,t,e,s,c,"static/chunks/pages/example/scatterplot-tooltip-with-voronoi-for-closest-point-detection-5a9a4215dc2f540f.js"],"/example/timeseries-moving-average":[a,t,e,s,r,"static/css/737f297697af8e75.css","static/chunks/pages/example/timeseries-moving-average-2461b9f5b0b20187.js"],"/fix-canvas-blurry-dataviz":[a,e,s,c,"static/chunks/pages/fix-canvas-blurry-dataviz-0f5665f678d67150.js"],"/heatmap":[a,t,e,s,i,"static/css/54771664905458da.css","static/chunks/pages/heatmap-71e07ca47a37103d.js"],"/hexbin-map":[a,t,e,s,i,c,"static/chunks/pages/hexbin-map-99453d28d36c6e74.js"],"/hierarchical-edge-bundling":[a,t,e,s,c,"static/chunks/pages/hierarchical-edge-bundling-fd6ca94961617e9c.js"],"/histogram":[a,t,e,o,s,i,r,p,"static/chunks/pages/histogram-e5200c648df817c5.js"],"/interactivity":[a,s,r,p,"static/chunks/pages/interactivity-7ca43c0c19947970.js"],"/line-chart":[a,t,e,o,s,i,r,p,"static/chunks/pages/line-chart-927189a8e9d2121c.js"],"/lollipop-plot":[a,t,e,o,s,i,r,"static/css/46c836e7a496aab6.css","static/chunks/pages/lollipop-plot-9b5c40befee60b29.js"],"/make-a-graph-responsive":[a,t,e,s,f,c,"static/chunks/pages/make-a-graph-responsive-54c7d37bac687a18.js"],"/map":[a,t,e,s,i,l,c,"static/chunks/pages/map-3cb1576844fe5161.js"],"/network-chart":[a,t,e,s,i,r,p,"static/chunks/pages/network-chart-b51ddd38466bd38d.js"],"/parallel-plot":[a,t,e,s,i,c,"static/chunks/pages/parallel-plot-e5d68ff4cd0d93e9.js"],"/pie-plot":[a,t,e,o,n,s,i,"static/css/2d55ec714184f95f.css","static/chunks/pages/pie-plot-627de5fc53195805.js"],"/radar-chart":[a,t,e,s,i,r,p,"static/chunks/pages/radar-chart-2275cd8c825f7675.js"],"/react-dataviz-animation-with-react-spring":[a,t,o,s,h,c,"static/chunks/pages/react-dataviz-animation-with-react-spring-443223440d38c735.js"],"/ridgeline":[a,t,e,s,i,r,u,p,"static/chunks/pages/ridgeline-449dd144bca04678.js"],"/sankey-diagram":[a,t,e,s,i,c,"static/chunks/pages/sankey-diagram-19a97dc46872907b.js"],"/scatter-plot":[a,t,e,s,i,r,d,b,"static/css/270731084cbdc85c.css","static/chunks/pages/scatter-plot-1c291c54c67f56ca.js"],"/shape-morphism-for-dataviz-with-react":[a,t,e,o,n,s,h,c,"static/chunks/pages/shape-morphism-for-dataviz-with-react-0ebc0c09a2e850bd.js"],"/stacked-area-plot":[a,t,e,o,n,s,i,k,"static/css/6a457c10c5ce26af.css","static/chunks/pages/stacked-area-plot-88f1f0e8e047d5bf.js"],"/stacked-barplot-with-negative-values":[a,t,s,m,c,"static/chunks/pages/stacked-barplot-with-negative-values-aa855da28d12c3bc.js"],"/streamchart":[a,t,e,o,n,s,i,k,"static/css/2b88bb4356e37def.css","static/chunks/pages/streamchart-efa36dd7f75cffba.js"],"/subscribe":[a,s,c,"static/chunks/pages/subscribe-252d98ebd6c86e52.js"],"/timeseries":[a,t,e,o,s,i,r,p,"static/chunks/pages/timeseries-f4bc20799e7f6303.js"],"/treemap":[a,t,e,s,g,"static/css/541a348b4668d195.css","static/chunks/pages/treemap-07098dcfa250908c.js"],"/typescript-d3-axis":[a,t,e,s,c,"static/chunks/pages/typescript-d3-axis-4c3b81bd97d47528.js"],"/violin-plot":[a,t,e,s,i,f,c,"static/chunks/pages/violin-plot-b2a3ec093b945883.js"],"/viz-from-the-future":[a,s,"static/css/b340902f13331342.css","static/chunks/pages/viz-from-the-future-5a5f6687159543a9.js"],"/voronoi":[a,t,e,s,i,r,p,"static/chunks/pages/voronoi-501b16cecc4add01.js"],"/what-is-a-color":[a,s,c,"static/chunks/pages/what-is-a-color-bd202c908100f7b1.js"],"/wordcloud":[a,t,e,s,c,"static/chunks/pages/wordcloud-5b4a401f67f7ddb4.js"],sortedPages:["/","/2d-density-plot","/404","/_app","/_error","/about","/add-hover-interaction-to-graph","/all","/animation","/arc-diagram","/area-plot","/articles","/barplot","/boxplot","/bubble-map","/bubble-plot","/build-axis-with-react","/cartogram","/chord-diagram","/choropleth-map","/circular-barplot","/circular-packing","/connected-scatter-plot","/connection-map","/correlogram","/cross-graph-highlight-interaction","/dataset-transition","/dendrogram","/density-plot","/donut","/example/arc-diagram-vertical","/example/barplot-data-transition-animation","/example/barplot-stacked-horizontal","/example/barplot-stacked-vertical","/example/boxplot-horizontal","/example/boxplot-jitter","/example/circle-packing-with-d3-force","/example/histogram-mirror","/example/histogram-small-multiple","/example/histogram-with-several-groups","/example/line-chart-synchronized-cursors","/example/network-diagram-with-colored-groups","/example/radar-chart-animation","/example/scatterplot-basic-canvas","/example/scatterplot-tooltip-with-voronoi-for-closest-point-detection","/example/timeseries-moving-average","/fix-canvas-blurry-dataviz","/heatmap","/hexbin-map","/hierarchical-edge-bundling","/histogram","/interactivity","/line-chart","/lollipop-plot","/make-a-graph-responsive","/map","/network-chart","/parallel-plot","/pie-plot","/radar-chart","/react-dataviz-animation-with-react-spring","/ridgeline","/sankey-diagram","/scatter-plot","/shape-morphism-for-dataviz-with-react","/stacked-area-plot","/stacked-barplot-with-negative-values","/streamchart","/subscribe","/timeseries","/treemap","/typescript-d3-axis","/violin-plot","/viz-from-the-future","/voronoi","/what-is-a-color","/wordcloud"]}}("static/chunks/3996-a4c96d7d78feb6f0.js","static/chunks/645-4872c822908c5080.js","static/chunks/7875-aadd425170e96677.js","static/chunks/5660-b8db8bc796807373.js","static/css/2247407c30b587b7.css","static/chunks/298-262f4755eac029e8.js","static/chunks/693-4a5fc90e80b9912a.js","static/chunks/2236-8bd9f36cdf4ac8bf.js","static/css/537902226fc25775.css","static/chunks/7303-913c346170e452f6.js","static/chunks/9421-5e6efef247940edd.js","static/chunks/2428-596304aec42c5d97.js","static/chunks/9142-8b575f64a3911647.js","static/chunks/5058-9d24a7b31eaedf24.js","static/chunks/8548-01181bf23ffbcfb5.js","static/chunks/8986-848154b8dc14ec20.js","static/chunks/7436-22099e6b70eb9b18.js","static/chunks/7022-dca9915a908fa916.js","static/chunks/3555-27c193c666fc06d4.js"),self.__BUILD_MANIFEST_CB&&self.__BUILD_MANIFEST_CB(); \ No newline at end of file diff --git a/_next/static/Tom4mSBFXG8ojMuGCMlo3/_ssgManifest.js b/_next/static/0bXDBMA-wxGoxt3q0CCX7/_ssgManifest.js similarity index 100% rename from _next/static/Tom4mSBFXG8ojMuGCMlo3/_ssgManifest.js rename to _next/static/0bXDBMA-wxGoxt3q0CCX7/_ssgManifest.js diff --git a/_next/static/chunks/pages/timeseries-fdae5d855aa440a8.js b/_next/static/chunks/pages/timeseries-f4bc20799e7f6303.js similarity index 63% rename from _next/static/chunks/pages/timeseries-fdae5d855aa440a8.js rename to _next/static/chunks/pages/timeseries-f4bc20799e7f6303.js index 30a904bf..caae9c34 100644 --- a/_next/static/chunks/pages/timeseries-fdae5d855aa440a8.js +++ b/_next/static/chunks/pages/timeseries-f4bc20799e7f6303.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[7007],{7726:function(e,t,i){(window.__NEXT_P=window.__NEXT_P||[]).push(["/timeseries",function(){return i(1323)}])},2450:function(e,t,i){"use strict";i.d(t,{Z:function(){return o}});var n=i(5893);i(7294);var s=i(2050),r=i(9975),a=i(9942);function o(e){let{images:t}=e,i=s.F.filter(e=>t.includes(e.img)).map((e,t)=>(0,n.jsx)(r.X,{link:e.link,title:e.title,description:(0,n.jsx)("p",{children:e.description}),img:e.img,alt:e.alt},t));return(0,n.jsx)(a.E,{children:i})}},1323:function(e,t,i){"use strict";i.r(t),i.d(t,{default:function(){return z}});var n=i(5893),s=i(7294),r=i(153),a=i(9965),o=i(1651),l=i(3572),c=i(1122),h=i(1664),d=i.n(h),m=i(88),x=i(7875);let u=e=>{let{width:t,height:i}=e;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("defs",{children:(0,n.jsx)("pattern",{id:"pattern_rkDsm",patternUnits:"userSpaceOnUse",width:"9.5",height:"2.5",patternTransform:"rotate(41)",children:(0,n.jsx)("line",{x1:"0",y:"0",x2:"0",y2:"9.5",stroke:"#D9B9F3",strokeWidth:"1"})})}),(0,n.jsx)("rect",{width:t,height:i,fill:"url(#pattern_rkDsm)",opacity:"1"})]})},p={top:30,right:30,bottom:50,left:50},f=e=>{let{width:t,height:i}=e,r=(0,s.useRef)(null),a=t-p.right-p.left,o=i-p.top-p.bottom,l=new Date("2020-12-01"),c=new Date("2023-06-01"),h=x.Xf().domain([l,c]).range([0,a]),d=(0,s.useMemo)(()=>x.BYU().domain([0,10]).range([o,0]),[i]);return(0,s.useEffect)(()=>{let e=x.Ys(r.current);e.selectAll("*").remove();let t=x.LLu(h);e.append("g").attr("transform","translate(0,"+o+")").call(t.ticks(8));let i=x.y4O(d);e.append("g").call(i)},[h,d,o]),(0,n.jsx)("div",{children:(0,n.jsxs)("svg",{width:t,height:i,style:{display:"inline-block"},children:[(0,n.jsx)("g",{width:a,height:o,transform:"translate(".concat([p.left,p.top].join(","),")"),children:(0,n.jsx)(u,{width:a,height:o})}),(0,n.jsx)("g",{width:a,height:o,ref:r,transform:"translate(".concat([p.left,p.top].join(","),")")})]})})},j=e=>{let{width:t=700,height:i=400}=e;return(0,n.jsx)(f,{width:t,height:i})};var g=i(7032),y=i(6438);let w=[{x:"2023-01-01",y:90},{x:"2023-02-01",y:12},{x:"2023-03-01",y:34},{x:"2023-04-01",y:53},{x:"2023-05-01",y:52},{x:"2023-06-01",y:9},{x:"2023-07-01",y:18},{x:"2023-08-01",y:78},{x:"2023-09-01",y:28},{x:"2023-12-01",y:34}],b={top:30,right:30,bottom:50,left:50},v=e=>{let{width:t,height:i,data:r}=e,a=(0,s.useRef)(null),o=t-b.right-b.left,l=i-b.top-b.bottom,c=x.Fp7(r,e=>e.y),h=x.BYU().domain([0,c||0]).range([l,0]),d=x.Z1g("%Y-%m-%d"),m=r.map(e=>d(e.x)).filter(e=>e instanceof Date),u=x.Wem(m),p=x.Xf().domain(u).range([0,o]);(0,s.useEffect)(()=>{let e=x.Ys(a.current);e.selectAll("*").remove();let t=x.LLu(p);e.append("g").attr("transform","translate(0,"+l+")").call(t);let i=x.y4O(h);e.append("g").call(i)},[p,h,l]);let f=x.jvg().x(e=>p(d(e.x))).y(e=>h(e.y)),j=f(r);return j?(0,n.jsx)("div",{children:(0,n.jsxs)("svg",{width:t,height:i,children:[(0,n.jsx)("g",{width:o,height:l,transform:"translate(".concat([b.left,b.top].join(","),")"),children:(0,n.jsx)("path",{d:j,opacity:1,stroke:"#9a6fb0",fill:"none",strokeWidth:2})}),(0,n.jsx)("g",{width:o,height:l,ref:a,transform:"translate(".concat([b.left,b.top].join(","),")")})]})}):null},k=e=>{let{width:t=700,height:i=400}=e;return(0,n.jsx)(v,{data:w,width:t,height:i})};var T=i(2450);let D=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("p",{children:["This section does not target a specific chart type, even though timeseries are often represented as ",(0,n.jsx)(d(),{href:"/line-chart",children:"line"})," charts or"," ",(0,n.jsx)(d(),{href:"/area",children:"area"})," charts."]}),(0,n.jsxs)("p",{children:["Instead, it provides a tips and tricks to deal with charts that represent the evolution in ",(0,n.jsx)("b",{children:"time"})," of a numeric variable. For instance, it provides hints on how to deal with ",(0,n.jsx)("b",{children:"dates"}),", how to ",(0,n.jsx)("b",{children:"pan"})," on a chart and more"]})]});function z(){return(0,n.jsxs)(r.A,{title:"Timeseries| The React Graph Gallery",seoDescription:"How to deal with timeseries with React and D3.js. A set of re-usable components coming with editable code and explanations.",children:[(0,n.jsx)(a.Z,{title:"Timeseries",description:D,chartType:"timeseries"}),(0,n.jsx)("h2",{id:"chart types",children:"Useful chart types"})," ",(0,n.jsxs)("p",{children:["This page is ",(0,n.jsx)("b",{children:"not"})," about a specific chart type. Instead it provides hints on how to deal with ",(0,n.jsx)("b",{children:"time"}),"."]}),(0,n.jsx)("p",{children:"Check the graph sections that are used to visualize timeseries below if there is a specific chart type you want to make."}),(0,n.jsx)("br",{}),(0,n.jsx)(T.Z,{images:["line-chart-basic.png","heatmapBasic.png","streamgraph-basic.png"]}),(0,n.jsx)("h2",{id:"date format",children:"The Date format"})," ",(0,n.jsxs)("p",{children:["The first struggle when dealing with timeseries is to work with the"," ",(0,n.jsx)("a",{href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date",children:"javascript Date format"}),". A ",(0,n.jsx)("code",{children:"Date"})," represents a single moment in time and is usually stored as a ",(0,n.jsx)("code",{children:"string"})," in the input dataset."]}),(0,n.jsxs)("p",{children:["Here is an ",(0,n.jsx)("b",{children:"FAQ"})," about the ",(0,n.jsx)("code",{children:"Date"})," format. I constantly forget how this works and come back here for reference. Note that it heavily relies on the"," ",(0,n.jsx)("a",{href:"https://github.com/d3/d3-time-format",children:"d3-time-format module"})," ","that provides great helpers."]}),(0,n.jsxs)(m.U,{startOpen:!1,title:(0,n.jsxs)("span",{children:["Transform a ",(0,n.jsx)("b",{children:"string"})," into a ",(0,n.jsx)("b",{children:"date"})]}),children:[(0,n.jsxs)("p",{children:["In your dataset, the date of each data point is probably stored as a string, like ",(0,n.jsx)("code",{children:"2015-06-01"})," for instance."]}),(0,n.jsxs)("p",{children:["In order to manipulate and plot those dates, you need to transform it into a"," ",(0,n.jsx)("a",{href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date",children:"javascript date format"}),"."]}),(0,n.jsx)(l.d,{code:F})]}),(0,n.jsxs)(m.U,{startOpen:!1,title:(0,n.jsxs)("span",{children:["Transform a ",(0,n.jsx)("b",{children:"date"})," into a ",(0,n.jsx)("b",{children:"string"})]}),children:[(0,n.jsxs)("p",{children:["Once you have a timestamp at the ",(0,n.jsx)("code",{children:"Date"})," format, you might want to display it on the screen using a specific format."]}),(0,n.jsx)(l.d,{code:_})]}),(0,n.jsxs)(m.U,{startOpen:!1,title:(0,n.jsxs)("span",{children:["What is the ",(0,n.jsx)("b",{children:"current date"})]}),children:[(0,n.jsxs)("p",{children:["You can use the ",(0,n.jsx)("code",{children:"Date.now()"})," function. Note that the date is returned as a ",(0,n.jsx)("code",{children:"number"}),"."]}),(0,n.jsx)(l.d,{code:A})]}),(0,n.jsx)("h2",{id:"time axis",children:"Building a time axis"}),(0,n.jsxs)("p",{children:["A very common task when it comes to build timeseries viz is to draw a"," ",(0,n.jsx)("b",{children:"time axis"}),". Fortunately, d3 has amazing helper functions allowing to create and draw temporal scales."]}),(0,n.jsxs)("p",{children:["All the magic is stored in the ",(0,n.jsx)("code",{children:"d3-scale"})," module, and more precisely in the"," ",(0,n.jsx)("a",{href:"https://github.com/d3/d3-scale#scaleTime",children:"scaleTime"})," ","function."]}),(0,n.jsx)("p",{children:"Building a time scale can be summarized as follow:"}),(0,n.jsx)(l.d,{code:C}),(0,n.jsxs)("p",{children:["Following this code block ",(0,n.jsx)("code",{children:"xScale"})," is a function. You give it a ",(0,n.jsx)("code",{children:"Date"}),", it returns a ",(0,n.jsx)("code",{children:"position in pixels"})]}),(0,n.jsxs)("p",{children:[" ","You can finally use this scale to draw the X axis using your favorite method:"]}),(0,n.jsxs)("ul",{children:[(0,n.jsx)("li",{children:"create your own react component"}),(0,n.jsxs)("li",{children:["call ",(0,n.jsx)("code",{children:"d3.axisBottom()"})," in a ",(0,n.jsx)("code",{children:"useEffect"})]})]}),(0,n.jsxs)("p",{children:["I'm preparing a full post on axes with d3 and react,"," ",(0,n.jsx)(d(),{href:"/subscribe",children:"subscribe"})," to the newsletter if you want to be notified when it's out!"]}),(0,n.jsx)(y.J,{size:"sm",href:"/subscribe",isFilled:!0,children:"More on axes"}),(0,n.jsx)(c.$,{vizName:"AxisTimeD3",VizComponent:j,height:250,maxWidth:600,caption:"A basic time axis build with d3.js and react."}),(0,n.jsxs)("p",{children:[(0,n.jsx)("code",{children:"d3"})," is very smart at picking the ",(0,n.jsx)("b",{children:"right label format"}),". If you're dealing with a very long period of time (years), it will display years. If you're dealing with a month, it will display days. And so on. It is very convenient. The logic controlling this formatting is provided ",(0,n.jsx)("a",{href:"https://gist.github.com/mbostock/4149176",children:"here"}),"."]}),(0,n.jsxs)("p",{children:["Note that you can ",(0,n.jsx)("b",{children:"customize"})," how dates are formatted along the X axis thanks to the ",(0,n.jsx)("code",{children:"tickFormat"})," function."]}),(0,n.jsx)("h2",{id:"line chart",children:"Line chart application"}),(0,n.jsxs)("p",{children:["If you already understood the content of the"," ",(0,n.jsx)(d(),{href:"line-chart",children:"line chart section"})," of the gallery, you just have to use a ",(0,n.jsx)("code",{children:"scaleTime"})," instead of a"," ",(0,n.jsx)("code",{children:"scaleLinear"})," and that's it, you have your first"," ",(0,n.jsx)("b",{children:"timeseries"})," visualization. \uD83D\uDE0B"]}),(0,n.jsx)(y.J,{size:"sm",href:"/line-chart",isFilled:!0,children:"Line chart section"}),(0,n.jsx)(c.$,{vizName:"LineChartDatasetTransition",VizComponent:k,height:300,maxWidth:900,caption:"A first timeseries line chart made thanks to the scaleTime function of d3."}),(0,n.jsx)("h2",{id:"synced cursor",children:"Synchronized cursor"}),(0,n.jsxs)("p",{children:["Another pretty common task when dealing with timeseries is to add a"," ",(0,n.jsx)("b",{children:"synchronized cursor"})," on all charts."]}),(0,n.jsxs)("p",{children:["This makes the dashboard more ",(0,n.jsx)("b",{children:"insightful"}),": hovering over an interesting part of a chart reveals where the timestamp is localized on other charts ",(0,n.jsx)("b",{children:"instantly"}),"."]}),(0,n.jsxs)("p",{children:["The implementation required to build a shared state between all charts of the webpage. Hovering a specific chart will update this state and thus update all other plots. This process is extensively described in this"," ",(0,n.jsx)(d(),{href:"/example/line-chart-synchronized-cursors",children:"synchronized cursor for timeseries"})," ","post."," "]}),(0,n.jsx)(y.J,{href:"/example/line-chart-synchronized-cursors",isFilled:!0,size:"sm",children:"Read full post"}),(0,n.jsx)(c.$,{vizName:"LineChartSyncCursor",VizComponent:g.e,height:300,maxWidth:900,caption:"Hover over a chart to see a cursor on both of them, easing the time comparison."}),(0,n.jsx)("h2",{id:"gallery",children:"Gallery of timeseries example"}),(0,n.jsxs)("p",{children:["On top of the generic use-cases presented above, here is a gallery of chart examples involving ",(0,n.jsx)("b",{children:"timeseries"})," visualization:"]}),(0,n.jsx)("br",{}),(0,n.jsx)(T.Z,{images:["timeseries-moving-average.png"]}),(0,n.jsx)("div",{className:"full-bleed border-t h-0 bg-gray-100 mb-3 mt-24"}),(0,n.jsx)(o.Z,{chartFamily:"evolution"}),(0,n.jsx)("div",{className:"mt-20"})]})}let F='\n// import the timeParse function from d3\nimport { timeParse } from "d3";\n\n// create a time parser function that works for our time format\nconst customTimeParser = timeParse("%Y-%m-%d");\n\n// convert a string into a date\nconst string = "2015-06-01"\nconst date = customTimeParser(string)\n\n// console.log(date)\n// Mon Jun 01 2015 00:00:00 GMT+0200 (Central European Summer Time)\n}\n'.trim(),_='\n// import the timeParse function from d3\nimport { timeFormat } from "d3";\n\n// create a time parser function that works for our time format\nconst customTimeFormatter = timeFormat("%B %d, %Y");\n\n// convert a string into a date\nconst date = new Date\nconst string = customTimeFormatter(date)\n\n// console.log(string)\n// "June 30, 2015"\n}\n'.trim(),A="\nconst now = Date.now()\n\n// console.log(now)\n// 1685004151406\n\nconst nowInDateFormat = new Date(now)\n\n// console.log(nowInDateFormat)\n// Thu May 25 2023 10:42:31 GMT+0200 (Central European Summer Time)\n}\n".trim(),C='\n// Start and end of the axis must be in the Date format\nconst start = new Date("2020-12-01");\nconst end = new Date("2023-06-01");\n\n// Use scaleTime() to create a time scale\nconst xScale = d3.scaleTime()\n .domain([start, end])\n .range([0, width]);\n'.trim()},7032:function(e,t,i){"use strict";i.d(t,{e:function(){return x}});var n=i(5893),s=i(7294);let r=[{x:1,y:40},{x:2,y:12},{x:3,y:34},{x:4,y:33},{x:5,y:22},{x:6,y:9},{x:7,y:18},{x:8,y:78},{x:9,y:28},{x:10,y:34}],a=[{x:1,y:90},{x:2,y:74},{x:3,y:84},{x:4,y:45},{x:5,y:65},{x:6,y:96},{x:7,y:65},{x:8,y:75},{x:9,y:58},{x:10,y:36}];var o=i(7875),l=i(6824);let c={top:30,right:30,bottom:50,left:50},h=e=>{var t;let{width:i,height:r,data:a,cursorPosition:l,setCursorPosition:h,color:m}=e,x=(0,s.useRef)(null),u=i-c.right-c.left,p=r-c.top-c.bottom,[f,j]=o.Wem(a,e=>e.y),g=(0,s.useMemo)(()=>o.BYU().domain([0,j||0]).range([p,0]),[a,r]),[y,w]=o.Wem(a,e=>e.x),b=(0,s.useMemo)(()=>o.BYU().domain([0,w||0]).range([0,u]),[a,i]);(0,s.useEffect)(()=>{let e=o.Ys(x.current);e.selectAll("*").remove();let t=o.LLu(b);e.append("g").attr("transform","translate(0,"+p+")").call(t);let i=o.y4O(g);e.append("g").call(i)},[b,g,p]);let v=o.jvg().x(e=>b(e.x)).y(e=>g(e.y)),k=v(a);if(!k)return null;let T=e=>{let t=b.invert(e),i=1/0,n=null;for(let e of a){let s=Math.abs(e.x-t);s{let t=e.currentTarget.getBoundingClientRect(),i=e.clientX-t.left,n=T(i);h(b(n.x))},onMouseLeave:()=>h(null),visibility:"hidden",pointerEvents:"all"})]}),(0,n.jsx)("g",{width:u,height:p,ref:x,transform:"translate(".concat([c.left,c.top].join(","),")")})]})})},d=e=>{let{x:t,y:i,height:s,color:r}=e,a=(0,l.q_)({to:{x:t,y:i}});return a.x?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(l.q.line,{x1:a.x,x2:a.x,y1:0,y2:s,stroke:"black",strokeWidth:1}),(0,n.jsx)("circle",{cx:t,cy:i,r:5,fill:r})]}):null},m=e=>{let{width:t=700,height:i=400}=e,[o,l]=(0,s.useState)(null);return(0,n.jsxs)("div",{style:{display:"flex"},children:[(0,n.jsx)(h,{data:r,width:t/2,height:i,cursorPosition:o,setCursorPosition:l,color:"#e85252"}),(0,n.jsx)(h,{data:a,width:t/2,height:i,cursorPosition:o,setCursorPosition:l,color:"#6689c6"})]})},x=e=>{let{width:t=700,height:i=400}=e;return(0,n.jsx)(m,{width:t,height:i})}},6824:function(e,t,i){"use strict";i.d(t,{q:function(){return n.q},q_:function(){return n.q_},to:function(){return n.to},vc:function(){return n.vc}});var n=i(2236)}},function(e){e.O(0,[3996,7875,5660,2236,645,298,693,9774,2888,179],function(){return e(e.s=7726)}),_N_E=e.O()}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[7007],{7726:function(e,t,i){(window.__NEXT_P=window.__NEXT_P||[]).push(["/timeseries",function(){return i(1323)}])},2450:function(e,t,i){"use strict";i.d(t,{Z:function(){return o}});var n=i(5893);i(7294);var s=i(2050),r=i(9975),a=i(9942);function o(e){let{images:t}=e,i=s.F.filter(e=>t.includes(e.img)).map((e,t)=>(0,n.jsx)(r.X,{link:e.link,title:e.title,description:(0,n.jsx)("p",{children:e.description}),img:e.img,alt:e.alt},t));return(0,n.jsx)(a.E,{children:i})}},1323:function(e,t,i){"use strict";i.r(t),i.d(t,{default:function(){return z}});var n=i(5893),s=i(7294),r=i(153),a=i(9965),o=i(1651),l=i(3572),c=i(1122),h=i(1664),d=i.n(h),m=i(88),x=i(7875);let u=e=>{let{width:t,height:i}=e;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("defs",{children:(0,n.jsx)("pattern",{id:"pattern_rkDsm",patternUnits:"userSpaceOnUse",width:"9.5",height:"2.5",patternTransform:"rotate(41)",children:(0,n.jsx)("line",{x1:"0",y:"0",x2:"0",y2:"9.5",stroke:"#D9B9F3",strokeWidth:"1"})})}),(0,n.jsx)("rect",{width:t,height:i,fill:"url(#pattern_rkDsm)",opacity:"1"})]})},p={top:30,right:30,bottom:50,left:50},f=e=>{let{width:t,height:i}=e,r=(0,s.useRef)(null),a=t-p.right-p.left,o=i-p.top-p.bottom,l=new Date("2020-12-01"),c=new Date("2023-06-01"),h=x.Xf().domain([l,c]).range([0,a]),d=(0,s.useMemo)(()=>x.BYU().domain([0,10]).range([o,0]),[i]);return(0,s.useEffect)(()=>{let e=x.Ys(r.current);e.selectAll("*").remove();let t=x.LLu(h);e.append("g").attr("transform","translate(0,"+o+")").call(t.ticks(8));let i=x.y4O(d);e.append("g").call(i)},[h,d,o]),(0,n.jsx)("div",{children:(0,n.jsxs)("svg",{width:t,height:i,style:{display:"inline-block"},children:[(0,n.jsx)("g",{width:a,height:o,transform:"translate(".concat([p.left,p.top].join(","),")"),children:(0,n.jsx)(u,{width:a,height:o})}),(0,n.jsx)("g",{width:a,height:o,ref:r,transform:"translate(".concat([p.left,p.top].join(","),")")})]})})},j=e=>{let{width:t=700,height:i=400}=e;return(0,n.jsx)(f,{width:t,height:i})};var g=i(7032),y=i(6438);let w=[{x:"2023-01-01",y:90},{x:"2023-02-01",y:12},{x:"2023-03-01",y:34},{x:"2023-04-01",y:53},{x:"2023-05-01",y:52},{x:"2023-06-01",y:9},{x:"2023-07-01",y:18},{x:"2023-08-01",y:78},{x:"2023-09-01",y:28},{x:"2023-12-01",y:34}],b={top:30,right:30,bottom:50,left:50},v=e=>{let{width:t,height:i,data:r}=e,a=(0,s.useRef)(null),o=t-b.right-b.left,l=i-b.top-b.bottom,c=x.Fp7(r,e=>e.y),h=x.BYU().domain([0,c||0]).range([l,0]),d=x.Z1g("%Y-%m-%d"),m=r.map(e=>d(e.x)).filter(e=>e instanceof Date),u=x.Wem(m),p=x.Xf().domain(u).range([0,o]);(0,s.useEffect)(()=>{let e=x.Ys(a.current);e.selectAll("*").remove();let t=x.LLu(p);e.append("g").attr("transform","translate(0,"+l+")").call(t);let i=x.y4O(h);e.append("g").call(i)},[p,h,l]);let f=x.jvg().x(e=>p(d(e.x))).y(e=>h(e.y)),j=f(r);return j?(0,n.jsx)("div",{children:(0,n.jsxs)("svg",{width:t,height:i,children:[(0,n.jsx)("g",{width:o,height:l,transform:"translate(".concat([b.left,b.top].join(","),")"),children:(0,n.jsx)("path",{d:j,opacity:1,stroke:"#9a6fb0",fill:"none",strokeWidth:2})}),(0,n.jsx)("g",{width:o,height:l,ref:a,transform:"translate(".concat([b.left,b.top].join(","),")")})]})}):null},k=e=>{let{width:t=700,height:i=400}=e;return(0,n.jsx)(v,{data:w,width:t,height:i})};var T=i(2450);let D=(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("p",{children:["This section does not target a specific chart type, even though timeseries are often represented as ",(0,n.jsx)(d(),{href:"/line-chart",children:"line"})," charts or"," ",(0,n.jsx)(d(),{href:"/area",children:"area"})," charts."]}),(0,n.jsxs)("p",{children:["Instead, it provides a tips and tricks to deal with charts that represent the evolution in ",(0,n.jsx)("b",{children:"time"})," of a numeric variable. For instance, it provides hints on how to deal with ",(0,n.jsx)("b",{children:"dates"}),", how to ",(0,n.jsx)("b",{children:"pan"})," on a chart and more"]})]});function z(){return(0,n.jsxs)(r.A,{title:"Timeseries| The React Graph Gallery",seoDescription:"How to deal with timeseries with React and D3.js. A set of re-usable components coming with editable code and explanations.",children:[(0,n.jsx)(a.Z,{title:"Timeseries",description:D,chartType:"timeseries"}),(0,n.jsx)("h2",{id:"chart types",children:"Useful chart types"})," ",(0,n.jsxs)("p",{children:["This page is ",(0,n.jsx)("b",{children:"not"})," about a specific chart type. Instead it provides hints on how to deal with ",(0,n.jsx)("b",{children:"time"}),"."]}),(0,n.jsx)("p",{children:"Check the graph sections that are used to visualize timeseries below if there is a specific chart type you want to make."}),(0,n.jsx)("br",{}),(0,n.jsx)(T.Z,{images:["line-chart-basic.png","heatmapBasic.png","streamgraph-basic.png"]}),(0,n.jsx)("h2",{id:"date format",children:"The Date format"})," ",(0,n.jsxs)("p",{children:["The first struggle when dealing with timeseries is to work with the"," ",(0,n.jsx)("a",{href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date",children:"javascript Date format"}),". A ",(0,n.jsx)("code",{children:"Date"})," represents a single moment in time and is usually stored as a ",(0,n.jsx)("code",{children:"string"})," in the input dataset."]}),(0,n.jsxs)("p",{children:["Here is an ",(0,n.jsx)("b",{children:"FAQ"})," about the ",(0,n.jsx)("code",{children:"Date"})," format. I constantly forget how this works and come back here for reference. Note that it heavily relies on the"," ",(0,n.jsx)("a",{href:"https://github.com/d3/d3-time-format",children:"d3-time-format module"})," ","that provides great helpers."]}),(0,n.jsxs)(m.U,{startOpen:!1,title:(0,n.jsxs)("span",{children:["Transform a ",(0,n.jsx)("b",{children:"string"})," into a ",(0,n.jsx)("b",{children:"date"})]}),children:[(0,n.jsxs)("p",{children:["In your dataset, the date of each data point is probably stored as a string, like ",(0,n.jsx)("code",{children:"2015-06-01"})," for instance."]}),(0,n.jsxs)("p",{children:["In order to manipulate and plot those dates, you need to transform it into a"," ",(0,n.jsx)("a",{href:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date",children:"javascript date format"}),"."]}),(0,n.jsx)(l.d,{code:F})]}),(0,n.jsxs)(m.U,{startOpen:!1,title:(0,n.jsxs)("span",{children:["Transform a ",(0,n.jsx)("b",{children:"date"})," into a ",(0,n.jsx)("b",{children:"string"})]}),children:[(0,n.jsxs)("p",{children:["Once you have a timestamp at the ",(0,n.jsx)("code",{children:"Date"})," format, you might want to display it on the screen using a specific format."]}),(0,n.jsx)(l.d,{code:_})]}),(0,n.jsxs)(m.U,{startOpen:!1,title:(0,n.jsxs)("span",{children:["What is the ",(0,n.jsx)("b",{children:"current date"})]}),children:[(0,n.jsxs)("p",{children:["You can use the ",(0,n.jsx)("code",{children:"Date.now()"})," function. Note that the date is returned as a ",(0,n.jsx)("code",{children:"number"}),"."]}),(0,n.jsx)(l.d,{code:A})]}),(0,n.jsx)("h2",{id:"time axis",children:"Building a time axis"}),(0,n.jsxs)("p",{children:["A very common task when it comes to build timeseries viz is to draw a"," ",(0,n.jsx)("b",{children:"time axis"}),". Fortunately, d3 has amazing helper functions allowing to create and draw temporal scales."]}),(0,n.jsxs)("p",{children:["All the magic is stored in the ",(0,n.jsx)("code",{children:"d3-scale"})," module, and more precisely in the"," ",(0,n.jsx)("a",{href:"https://github.com/d3/d3-scale#scaleTime",children:"scaleTime"})," ","function."]}),(0,n.jsx)("p",{children:"Building a time scale can be summarized as follow:"}),(0,n.jsx)(l.d,{code:C}),(0,n.jsxs)("p",{children:["Following this code block ",(0,n.jsx)("code",{children:"xScale"})," is a function. You give it a ",(0,n.jsx)("code",{children:"Date"}),", it returns a ",(0,n.jsx)("code",{children:"position in pixels"})]}),(0,n.jsxs)("p",{children:[" ","You can finally use this scale to draw the X axis using your favorite method:"]}),(0,n.jsxs)("ul",{children:[(0,n.jsx)("li",{children:"create your own react component"}),(0,n.jsxs)("li",{children:["call ",(0,n.jsx)("code",{children:"d3.axisBottom()"})," in a ",(0,n.jsx)("code",{children:"useEffect"})]})]}),(0,n.jsxs)("p",{children:["I'm preparing a full post on axes with d3 and react,"," ",(0,n.jsx)(d(),{href:"/subscribe",children:"subscribe"})," to the newsletter if you want to be notified when it's out!"]}),(0,n.jsx)(y.J,{size:"sm",href:"/subscribe",isFilled:!0,children:"More on axes"}),(0,n.jsx)(c.$,{vizName:"AxisTimeD3",VizComponent:j,height:250,maxWidth:600,caption:"A basic time axis build with d3.js and react."}),(0,n.jsxs)("p",{children:[(0,n.jsx)("code",{children:"d3"})," is very smart at picking the ",(0,n.jsx)("b",{children:"right label format"}),". If you're dealing with a very long period of time (years), it will display years. If you're dealing with a month, it will display days. And so on. It is very convenient. The logic controlling this formatting is provided ",(0,n.jsx)("a",{href:"https://gist.github.com/mbostock/4149176",children:"here"}),"."]}),(0,n.jsxs)("p",{children:["Note that you can ",(0,n.jsx)("b",{children:"customize"})," how dates are formatted along the X axis thanks to the ",(0,n.jsx)("code",{children:"tickFormat"})," function."]}),(0,n.jsx)("h2",{id:"line chart",children:"Line chart application"}),(0,n.jsxs)("p",{children:["If you already understood the content of the"," ",(0,n.jsx)(d(),{href:"line-chart",children:"line chart section"})," of the gallery, you just have to use a ",(0,n.jsx)("code",{children:"scaleTime"})," instead of a"," ",(0,n.jsx)("code",{children:"scaleLinear"})," and that's it, you have your first"," ",(0,n.jsx)("b",{children:"timeseries"})," visualization. \uD83D\uDE0B"]}),(0,n.jsx)(y.J,{size:"sm",href:"/line-chart",isFilled:!0,children:"Line chart section"}),(0,n.jsx)(c.$,{vizName:"LineChartTime",VizComponent:k,height:300,maxWidth:900,caption:"A first timeseries line chart made thanks to the scaleTime function of d3."}),(0,n.jsx)("h2",{id:"synced cursor",children:"Synchronized cursor"}),(0,n.jsxs)("p",{children:["Another pretty common task when dealing with timeseries is to add a"," ",(0,n.jsx)("b",{children:"synchronized cursor"})," on all charts."]}),(0,n.jsxs)("p",{children:["This makes the dashboard more ",(0,n.jsx)("b",{children:"insightful"}),": hovering over an interesting part of a chart reveals where the timestamp is localized on other charts ",(0,n.jsx)("b",{children:"instantly"}),"."]}),(0,n.jsxs)("p",{children:["The implementation required to build a shared state between all charts of the webpage. Hovering a specific chart will update this state and thus update all other plots. This process is extensively described in this"," ",(0,n.jsx)(d(),{href:"/example/line-chart-synchronized-cursors",children:"synchronized cursor for timeseries"})," ","post."," "]}),(0,n.jsx)(y.J,{href:"/example/line-chart-synchronized-cursors",isFilled:!0,size:"sm",children:"Read full post"}),(0,n.jsx)(c.$,{vizName:"LineChartSyncCursor",VizComponent:g.e,height:300,maxWidth:900,caption:"Hover over a chart to see a cursor on both of them, easing the time comparison."}),(0,n.jsx)("h2",{id:"gallery",children:"Gallery of timeseries example"}),(0,n.jsxs)("p",{children:["On top of the generic use-cases presented above, here is a gallery of chart examples involving ",(0,n.jsx)("b",{children:"timeseries"})," visualization:"]}),(0,n.jsx)("br",{}),(0,n.jsx)(T.Z,{images:["timeseries-moving-average.png"]}),(0,n.jsx)("div",{className:"full-bleed border-t h-0 bg-gray-100 mb-3 mt-24"}),(0,n.jsx)(o.Z,{chartFamily:"evolution"}),(0,n.jsx)("div",{className:"mt-20"})]})}let F='\n// import the timeParse function from d3\nimport { timeParse } from "d3";\n\n// create a time parser function that works for our time format\nconst customTimeParser = timeParse("%Y-%m-%d");\n\n// convert a string into a date\nconst string = "2015-06-01"\nconst date = customTimeParser(string)\n\n// console.log(date)\n// Mon Jun 01 2015 00:00:00 GMT+0200 (Central European Summer Time)\n}\n'.trim(),_='\n// import the timeParse function from d3\nimport { timeFormat } from "d3";\n\n// create a time parser function that works for our time format\nconst customTimeFormatter = timeFormat("%B %d, %Y");\n\n// convert a string into a date\nconst date = new Date\nconst string = customTimeFormatter(date)\n\n// console.log(string)\n// "June 30, 2015"\n}\n'.trim(),A="\nconst now = Date.now()\n\n// console.log(now)\n// 1685004151406\n\nconst nowInDateFormat = new Date(now)\n\n// console.log(nowInDateFormat)\n// Thu May 25 2023 10:42:31 GMT+0200 (Central European Summer Time)\n}\n".trim(),C='\n// Start and end of the axis must be in the Date format\nconst start = new Date("2020-12-01");\nconst end = new Date("2023-06-01");\n\n// Use scaleTime() to create a time scale\nconst xScale = d3.scaleTime()\n .domain([start, end])\n .range([0, width]);\n'.trim()},7032:function(e,t,i){"use strict";i.d(t,{e:function(){return x}});var n=i(5893),s=i(7294);let r=[{x:1,y:40},{x:2,y:12},{x:3,y:34},{x:4,y:33},{x:5,y:22},{x:6,y:9},{x:7,y:18},{x:8,y:78},{x:9,y:28},{x:10,y:34}],a=[{x:1,y:90},{x:2,y:74},{x:3,y:84},{x:4,y:45},{x:5,y:65},{x:6,y:96},{x:7,y:65},{x:8,y:75},{x:9,y:58},{x:10,y:36}];var o=i(7875),l=i(6824);let c={top:30,right:30,bottom:50,left:50},h=e=>{var t;let{width:i,height:r,data:a,cursorPosition:l,setCursorPosition:h,color:m}=e,x=(0,s.useRef)(null),u=i-c.right-c.left,p=r-c.top-c.bottom,[f,j]=o.Wem(a,e=>e.y),g=(0,s.useMemo)(()=>o.BYU().domain([0,j||0]).range([p,0]),[a,r]),[y,w]=o.Wem(a,e=>e.x),b=(0,s.useMemo)(()=>o.BYU().domain([0,w||0]).range([0,u]),[a,i]);(0,s.useEffect)(()=>{let e=o.Ys(x.current);e.selectAll("*").remove();let t=o.LLu(b);e.append("g").attr("transform","translate(0,"+p+")").call(t);let i=o.y4O(g);e.append("g").call(i)},[b,g,p]);let v=o.jvg().x(e=>b(e.x)).y(e=>g(e.y)),k=v(a);if(!k)return null;let T=e=>{let t=b.invert(e),i=1/0,n=null;for(let e of a){let s=Math.abs(e.x-t);s{let t=e.currentTarget.getBoundingClientRect(),i=e.clientX-t.left,n=T(i);h(b(n.x))},onMouseLeave:()=>h(null),visibility:"hidden",pointerEvents:"all"})]}),(0,n.jsx)("g",{width:u,height:p,ref:x,transform:"translate(".concat([c.left,c.top].join(","),")")})]})})},d=e=>{let{x:t,y:i,height:s,color:r}=e,a=(0,l.q_)({to:{x:t,y:i}});return a.x?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(l.q.line,{x1:a.x,x2:a.x,y1:0,y2:s,stroke:"black",strokeWidth:1}),(0,n.jsx)("circle",{cx:t,cy:i,r:5,fill:r})]}):null},m=e=>{let{width:t=700,height:i=400}=e,[o,l]=(0,s.useState)(null);return(0,n.jsxs)("div",{style:{display:"flex"},children:[(0,n.jsx)(h,{data:r,width:t/2,height:i,cursorPosition:o,setCursorPosition:l,color:"#e85252"}),(0,n.jsx)(h,{data:a,width:t/2,height:i,cursorPosition:o,setCursorPosition:l,color:"#6689c6"})]})},x=e=>{let{width:t=700,height:i=400}=e;return(0,n.jsx)(m,{width:t,height:i})}},6824:function(e,t,i){"use strict";i.d(t,{q:function(){return n.q},q_:function(){return n.q_},to:function(){return n.to},vc:function(){return n.vc}});var n=i(2236)}},function(e){e.O(0,[3996,7875,5660,2236,645,298,693,9774,2888,179],function(){return e(e.s=7726)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/about.html b/about.html index fe8bfbfe..5ede4947 100644 --- a/about.html +++ b/about.html @@ -1 +1 @@ -About the gallery

React + D3.js = ❀️


A love story – So simple powerful yet so complicated

A few years ago I created the d3 graph gallery, a website showcasing hundreds of simple charts made with d3.js. It worked well! Thousands of people use it daily to learn d3. πŸŽ‰

Since then, React became the most popular framework to build user interfaces. This rose a question: how to build a chart in react? That's a complicated question with many answers. Here are the 3 most common approaches.

3 ways to draw a chart in react

β†’ 1️⃣ Charting libraries

There is a myriad of charting libraries offering react components for every chart type. HighChart, ReCharts, React-viz, plot, visX and so many more. Those libraries are awesome: you'll get a working chart in minutes using them.

But simplicity comes with a cost: the time you saved in the first place will be lost when you'll try to reach a high level of customization.

If you want to build something unique, you need to draw shapes one by one.

β†’ 2️⃣ D3 for rendering in a useEffect hook

If you're familiar with d3.js already, it's possible to use any of its examples (from a block or the gallery) by using a useEffect hook.

Basically, you can create a div in the DOM using react. You can then use the drawing methods of the d3-selection module like append or axisBottom to target this div, and add the content of the chart.

Let's apply this to draw axes:

You can use all the d3 knowlege you have in a useEffect hook to build the graph in a react context.

This works but comes with some caveats. To put it in a nutshell you now have 2 tools trying to control the DOM: react and d3. That's hard to maintain for large applications.

β†’ 3️⃣ D3 for maths, React for rendering

This gallery suggests using d3.js only for the math utils it provides. And to add entries to the DOM using react, like for any other UI element.

Let's say we want to build a scatterplot. The scaleLinear function of d3.js is used to build the scales. Now that we can easily know the position of a circle on the screen, we can just loop through all data items and render them as a circle svg element.

012345678910

Use d3.js to compute the scales. Use React to render the circles.

Learn concepts, Get templates

This gallery is all about using the power of the d3 math utils and the react rendering engine.

The first goal is to teach the concepts. Many examples are provided for each chart type. Each one targets a specific theme like color, axis, responsiveness, hover effect, or tooltips.

The second goal is to provide templates for each viz type. Building a viz from scratch is time-consuming, so better tweak an existing example.

All graph examples come with an explanation and a code sandbox allowing you to play with the code.

I built this website with ❀️. I hope it will help you create stunning vizs in a minimum amount of time. Reach me on Twitter, contribute on github and subscribe to the newsletter to know when new chart types are published!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +About the gallery

React + D3.js = ❀️


A love story – So simple powerful yet so complicated

A few years ago I created the d3 graph gallery, a website showcasing hundreds of simple charts made with d3.js. It worked well! Thousands of people use it daily to learn d3. πŸŽ‰

Since then, React became the most popular framework to build user interfaces. This rose a question: how to build a chart in react? That's a complicated question with many answers. Here are the 3 most common approaches.

3 ways to draw a chart in react

β†’ 1️⃣ Charting libraries

There is a myriad of charting libraries offering react components for every chart type. HighChart, ReCharts, React-viz, plot, visX and so many more. Those libraries are awesome: you'll get a working chart in minutes using them.

But simplicity comes with a cost: the time you saved in the first place will be lost when you'll try to reach a high level of customization.

If you want to build something unique, you need to draw shapes one by one.

β†’ 2️⃣ D3 for rendering in a useEffect hook

If you're familiar with d3.js already, it's possible to use any of its examples (from a block or the gallery) by using a useEffect hook.

Basically, you can create a div in the DOM using react. You can then use the drawing methods of the d3-selection module like append or axisBottom to target this div, and add the content of the chart.

Let's apply this to draw axes:

You can use all the d3 knowlege you have in a useEffect hook to build the graph in a react context.

This works but comes with some caveats. To put it in a nutshell you now have 2 tools trying to control the DOM: react and d3. That's hard to maintain for large applications.

β†’ 3️⃣ D3 for maths, React for rendering

This gallery suggests using d3.js only for the math utils it provides. And to add entries to the DOM using react, like for any other UI element.

Let's say we want to build a scatterplot. The scaleLinear function of d3.js is used to build the scales. Now that we can easily know the position of a circle on the screen, we can just loop through all data items and render them as a circle svg element.

012345678910

Use d3.js to compute the scales. Use React to render the circles.

Learn concepts, Get templates

This gallery is all about using the power of the d3 math utils and the react rendering engine.

The first goal is to teach the concepts. Many examples are provided for each chart type. Each one targets a specific theme like color, axis, responsiveness, hover effect, or tooltips.

The second goal is to provide templates for each viz type. Building a viz from scratch is time-consuming, so better tweak an existing example.

All graph examples come with an explanation and a code sandbox allowing you to play with the code.

I built this website with ❀️. I hope it will help you create stunning vizs in a minimum amount of time. Reach me on Twitter, contribute on github and subscribe to the newsletter to know when new chart types are published!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/add-hover-interaction-to-graph.html b/add-hover-interaction-to-graph.html index 75954f0f..0d452d1c 100644 --- a/add-hover-interaction-to-graph.html +++ b/add-hover-interaction-to-graph.html @@ -1,4 +1,4 @@ -Hover interaction on a chart with React

Hover interaction on a chart with React


Interactivity is an important part of dataviz when working in the browser. Adding a hover effect can improve the user experience by highlighting a series on the chart. Here are a couple way to implement it, always keeping performances in mind.

40608002000040000

Experimenting with different highlight strategies on a scatterplot. From left to right: using a :hover pseudo class | using the pseudo class AND dimming.

-Using the :hover css pseudo class

A CSS pseudo-class is a keyword added to a selector that specifies a special y of the selected element(s) (mdn doc).

Basically, it means that you can add a class to each shape of a graph, and change its appearance when the user hover over it.

For instance, the scatterplot below is composed by a myriad of circle elements, each having a .scatterplotCircle class. In the css file, I can use .scatterplotCircle to style the circles, and .scatterplotCircle:hover to style the hovered circles. πŸŽ‰

3540455055606570758085

Scatterplot with hover highlight

Pro: This is the most basic strategy. It is very easy to implement and has good performances since there is nothing that needs to be redrawn expect the highlighted point.
Con: Not the best design: all the other circles are still very prominent so the highlight isn't strong.Works only to highlight the hovered circle. If the information of the circle to highlight comes as a prop, we need something else.

-Dim other groups, css only

More elegant in term of design. Requires to dim all series by adding a class to the parent div. Then highlight the hovered shape by removing it's dim.

Do it for treemap

.circle {
+Hover interaction on a chart with React

Hover interaction on a chart with React


Interactivity is an important part of dataviz when working in the browser. Adding a hover effect can improve the user experience by highlighting a series on the chart. Here are a couple way to implement it, always keeping performances in mind.

40608002000040000

Experimenting with different highlight strategies on a scatterplot. From left to right: using a :hover pseudo class | using the pseudo class AND dimming.

-Using the :hover css pseudo class

A CSS pseudo-class is a keyword added to a selector that specifies a special y of the selected element(s) (mdn doc).

Basically, it means that you can add a class to each shape of a graph, and change its appearance when the user hover over it.

For instance, the scatterplot below is composed by a myriad of circle elements, each having a .scatterplotCircle class. In the css file, I can use .scatterplotCircle to style the circles, and .scatterplotCircle:hover to style the hovered circles. πŸŽ‰

3540455055606570758085

Scatterplot with hover highlight

Pro: This is the most basic strategy. It is very easy to implement and has good performances since there is nothing that needs to be redrawn expect the highlighted point.
Con: Not the best design: all the other circles are still very prominent so the highlight isn't strong.Works only to highlight the hovered circle. If the information of the circle to highlight comes as a prop, we need something else.

-Dim other groups, css only

More elegant in term of design. Requires to dim all series by adding a class to the parent div. Then highlight the hovered shape by removing it's dim.

Do it for treemap

.circle {
   fill-opacity: 1;
 }
 .svgArea:hover .circle {
@@ -6,4 +6,4 @@
 }
 .svgArea .circle:hover {
   fill-opacity: 1;
-}
Mark90Robert12Emily34Marion53Nicolas98Malki22DjΓ©12MΓ©lanie45Einstein76

Hover over a group on the treemap to see the other groups fading.

Pro: Better design. Easy to implement.
Con: If mouse enter chart area withouth hovering a circle, I'm still fading everything. I can highlight a circle that is below another. Perf issue if many dots?

-Dim other groups, toggle class in js

More elegant in term of design. Requires to dim all series by adding a class to the parent div. Then highlight the hovered shape by removing it's dim.

Mark (90)Robert (12)Emily (34)Marion (53)Nicolas (58)

A donut chart with clean inline legends, built thanks to the centroid function of d3.js.

-Canvas and second layer for performances

Using the useDimensions hook described above is pretty straight-forward. You first need to create a ref using the react useRef()function:

Use dimming to highlight a specific point





Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}
Mark90Robert12Emily34Marion53Nicolas98Malki22DjΓ©12MΓ©lanie45Einstein76

Hover over a group on the treemap to see the other groups fading.

Pro: Better design. Easy to implement.
Con: If mouse enter chart area withouth hovering a circle, I'm still fading everything. I can highlight a circle that is below another. Perf issue if many dots?

-Dim other groups, toggle class in js

More elegant in term of design. Requires to dim all series by adding a class to the parent div. Then highlight the hovered shape by removing it's dim.

Mark (90)Robert (12)Emily (34)Marion (53)Nicolas (58)

A donut chart with clean inline legends, built thanks to the centroid function of d3.js.

-Canvas and second layer for performances

Using the useDimensions hook described above is pretty straight-forward. You first need to create a ref using the react useRef()function:

Use dimming to highlight a specific point





Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/all.html b/all.html index ac7c3e74..eb0a59c5 100644 --- a/all.html +++ b/all.html @@ -1 +1 @@ -All graphs

All graphs

Dataviz logo representing a DataArt2 chart.

The react graph gallery displays hundreds of graphs made with React, often with the help of d3.js. This page provides an overview of all charts showcased in this gallery.

Note that all chart types are presented on the welcome page of the gallery. It is probably a more convenient way to browse this website if you know what you are looking for!

Useful links
Picture of an empty chart area with X and Y axes

Scales and axes

How to map your data in a 2d space, and how to draw the axes

GIF of a scatterplot with hover effect

Scatterplot Hover effect

How to add a hover effect to highlight a group on a scatterplot

Most basic scatterplot made with react and d3

Basic scatter plot

Add circles to get a basic scatter plot

Scatterplot with tooltip made with react and d3

Add tooltip

Get more details about each datapoint by adding a tooltip on hover

Scatterplot with hover effect made with react and d3

Add a hover effect

Highlight a specific group on hover

Real life example of a scatterplot made with react and d3

Real life use-case

Reproduction of a data wrapper chart representing countries CO2 data

gif of a scatterplot with voronoi diagram for closest point detection

Closest point detection with Voronoi

Using a voronoi diagram in the scatterplot background is a smart way to efficiently find the mouse closest point

a scatterplot made with react and rendered in canvas

Scatterplot in Canvas

Learn how to render a scatterplot in canvas to improve performances

Picture of a simple heatmap made with react and d3.js

Basic heatmap

Most basic heatmap

Picture of a heatmap with a tooltip that appears on hover

Heatmap with tooltip

Learn how to add a tooltip to a heatmap with react

Picture of a continuous color scale built with d3.js

Continuous color scale

How to add a color legend to your chart that uses a continuous color scale

Picture of a heatmap showing the effect of vaccination, built with react and d3

Vaccination heatmap

Reproduction of a famous vaccination heatmap using d3 and react

Picture of a correlogram built with react and d3

Basic correlogram

Learn how to build a correlogram with react and d3

Picture of a simple bubble plot with a legend made with react and d3.js

Bubble plot

Learn how to build a bubble plot with react and d3.js

GIF of a bubble plot smoothly transitioning data

Bubble plot data set transition

How to smoothly animate the transition between dataset

Picture of a hexbin chart made with React and d3.js

Hexbin chart

A hexbin chart split the figure in hexagons to show a 2d density

Picture of a connected scatter plot made with React and d3.js

Simple connected scatterplot

A very simple connected scatter plot showing the evolution of 1 numeric variable

gif of a violin plot smoothly transitioning to a boxplot using shape morphism

Violin to Boxplot transition

Using shape morphism to smoothly transition from a boxplot to a violin and reverse

GIF showing a violin plot with varying bucket size

Bucket size effect

Interactive example showing the bucket size effect on a violin chart

Picture of a violin shape built with react and d3

Violin shape

How to build the shape of a violin with SVG

GIF showing a mirror transition between a boxplot and a violin plot

Boxplot to Violin plot

Interactive example showing the difference between a boxplot and a violin

Picture of a basic violin chart built in react

Basic violin plot

Learn how to build a basic violin chart with d3 and react

Picture of a violin plot with variable bucket size

Violin with variable bucket size

A violin plot with a slider to change the bucket size in use

Picture of a basic density plot built with React and d3

Basic density plot

Most basic density plot built with React and d3

Picture of a density plot with multiple groups

Density plot with multiple groups

How to add several groups on the same density plot

Picture of a simple histogram made with react and d3.js

Histogram

Learn how to build a histogram with react and d3.js

GIF of a histogram with animated data transition

Histogram dataset transition

How to animate the transition between datasets

picture of a mirror histogram made with react and d3.js

Mirror histogram

Create a mirror histogram to compare the distribution of 2 groups in a dataset

Picture of a histogram with small multiple built with react and d3.js

Small multiple

Create one panel per group to show its distribution separately

Picture of a histogram with multiple groups built with react and d3.js

Multiple groups

A histogram with <b>multiple</b> groups displayed on the same axis.

Picture of a boxplot with jitter built using react and d3.js

Boxplot with jitter

Add individual data points using jitter on top of the boxplot

Picture of a box component, allowing to build a boxplot later on

Boxplot shape

How to build a boxplot shape in SVG

Picture of a basic boxplot built with react and d3

Basic boxplot

How to build a basic boxplot with react

Picture of a horizontal boxplot built with react and d3

Horizontal boxplot

How to build a horizontal boxplot with react

Picture of a basic ridgeline chart built with react and d3

Basic ridgeline chart

Most basic version of a ridgeline plot

Picture of a horizontal barplot made with React and d3

Basic barplot

Most basic barplot built with React and d3

GIF of a data update on a React barplot

Barplot dataset transition

How to smoothly animate the transition between dataset

Picture of a stacked barchart made with react and d3

Horizontal Stacked Barplot

Represent group and subgroup values by stacking the data

Picture of a vertical stacked barchart made with react and d3

Vertical Stacked Barplot

Represent group and subgroup values by stacking the data

Picture of a very simple lollipop chart

Most basic lollipop plot

Learn how to build a very simple lollipop chart with React and D3.js

Picture of a very simple dumbbell chart

Most basic dumbbell plot

Learn how to build a very simple dumbbell chart with React and D3.js

Picture of a lollipop chart with hover effect

Lollipop with hover effect

Learn how to add a hover effect to your lollipop chart

Picture of a lollipop with buttons and animated transition

Animation between dataset

Learn how to build a smooth animated transition between 2 datasets

Picture of the background grid of a radar chart

Most basic line chart

Learn how to build the background grid of a radar chart

Picture of a very simple radar chart with 1 group only made with react and d3

Most basic radar chart

The most basic radar chart one can make using d3 and react

Picture of a radar chart made with react and d3, with several groups displayed on the figure.

Multi-group radar chart

Radar chart with several groups displayed

GIF of a radar chart, a line chart and a lollipop that animate between dataset

Radar chart, line chart an lollipop with animated transition

Three charts connected to same buttons, with smooth, synchronized animation when a button is clicked

Picture of a very simple line chart made with react and d3

Most basic line chart

The most basic line chart one can make using d3 and react

GIF of a line chart that animates between 2 dataset

Line chart with dataset transition

How to smoothly animate the transition between 2 dataset on a line chart

line charts with synchronized cursors

Synchronized cursors

Add a cursor synchronized on all your charts

Picture of a basic area chart made with React and D3

Basic Area Chart

Most basic version of an area chart made with react and d3.js

picture of a basic stacked area plot made with react

Basis stacked area chart

Most basic version of a stacked area chart. Explains how to use the stack() function of d3.js

Picture of a basic streamgraph made using Reacrt and d3.js

Basic Streamgraph

Most basic streamgraph one can build using d3 and react

GIF of a streamgraph react component that supports hover effect

Streamgraph with hover effect

How to add a hover effect on a streamgraph to highlight a group

GIF of a streamgraph

Offset and Smoothing transition

An interactive streamgraph example showing how to animate transition between the chart stacking features.

GIF of a streamgraph with multiple interactive features

Streamgraph application

Streamgraph with a slider to zoom on a time stamp and with interactive inline legends

Picture of a timeseries chart made with React and D3.js: scatterplot and line chart in use.

Timeseries with moving average

A scatterplot used for timeseries, with the moving average shown as a line chart on top.

Picture of a very basic circle packing chart

Most basic circular packing chart

The most basic circular packing chart one can make using d3.js and React.

Picture of a very basic circle packing chart with 2 levels of hierarchy

Circular packing: 2 levels of hierarchy

A simple circular packing chart with 2 levels of hierarchy built with React and d3.

Picture of a circle packing chart made using the d3-force plugin

Circle Pack with d3-force

Another approach to build a circle packing chart using physical forces to compute node positions.

Picture of a vertical arc diagram

Vertical arc diagram

The vertical version of the arc diagram is more convenient to display labels

Picture of a very simple network chart built with React and D3.js.

Most basic network chart

Most basic network chart using the d3-force plugin to apply physical forces.

Picture of a playground allowing to play with the various d3 forces

Play with forces

A playground to discover the effect of the various forces you can apply to your particles

Picture of a force directed network chart showing character co-occurence in les miserables

Force directed graph

A force directed network chart showing character co-occurence in les miserables

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +All graphs

All graphs

Dataviz logo representing a DataArt2 chart.

The react graph gallery displays hundreds of graphs made with React, often with the help of d3.js. This page provides an overview of all charts showcased in this gallery.

Note that all chart types are presented on the welcome page of the gallery. It is probably a more convenient way to browse this website if you know what you are looking for!

Useful links
Picture of an empty chart area with X and Y axes

Scales and axes

How to map your data in a 2d space, and how to draw the axes

GIF of a scatterplot with hover effect

Scatterplot Hover effect

How to add a hover effect to highlight a group on a scatterplot

Most basic scatterplot made with react and d3

Basic scatter plot

Add circles to get a basic scatter plot

Scatterplot with tooltip made with react and d3

Add tooltip

Get more details about each datapoint by adding a tooltip on hover

Scatterplot with hover effect made with react and d3

Add a hover effect

Highlight a specific group on hover

Real life example of a scatterplot made with react and d3

Real life use-case

Reproduction of a data wrapper chart representing countries CO2 data

gif of a scatterplot with voronoi diagram for closest point detection

Closest point detection with Voronoi

Using a voronoi diagram in the scatterplot background is a smart way to efficiently find the mouse closest point

a scatterplot made with react and rendered in canvas

Scatterplot in Canvas

Learn how to render a scatterplot in canvas to improve performances

Picture of a simple heatmap made with react and d3.js

Basic heatmap

Most basic heatmap

Picture of a heatmap with a tooltip that appears on hover

Heatmap with tooltip

Learn how to add a tooltip to a heatmap with react

Picture of a continuous color scale built with d3.js

Continuous color scale

How to add a color legend to your chart that uses a continuous color scale

Picture of a heatmap showing the effect of vaccination, built with react and d3

Vaccination heatmap

Reproduction of a famous vaccination heatmap using d3 and react

Picture of a correlogram built with react and d3

Basic correlogram

Learn how to build a correlogram with react and d3

Picture of a simple bubble plot with a legend made with react and d3.js

Bubble plot

Learn how to build a bubble plot with react and d3.js

GIF of a bubble plot smoothly transitioning data

Bubble plot data set transition

How to smoothly animate the transition between dataset

Picture of a hexbin chart made with React and d3.js

Hexbin chart

A hexbin chart split the figure in hexagons to show a 2d density

Picture of a connected scatter plot made with React and d3.js

Simple connected scatterplot

A very simple connected scatter plot showing the evolution of 1 numeric variable

gif of a violin plot smoothly transitioning to a boxplot using shape morphism

Violin to Boxplot transition

Using shape morphism to smoothly transition from a boxplot to a violin and reverse

GIF showing a violin plot with varying bucket size

Bucket size effect

Interactive example showing the bucket size effect on a violin chart

Picture of a violin shape built with react and d3

Violin shape

How to build the shape of a violin with SVG

GIF showing a mirror transition between a boxplot and a violin plot

Boxplot to Violin plot

Interactive example showing the difference between a boxplot and a violin

Picture of a basic violin chart built in react

Basic violin plot

Learn how to build a basic violin chart with d3 and react

Picture of a violin plot with variable bucket size

Violin with variable bucket size

A violin plot with a slider to change the bucket size in use

Picture of a basic density plot built with React and d3

Basic density plot

Most basic density plot built with React and d3

Picture of a density plot with multiple groups

Density plot with multiple groups

How to add several groups on the same density plot

Picture of a simple histogram made with react and d3.js

Histogram

Learn how to build a histogram with react and d3.js

GIF of a histogram with animated data transition

Histogram dataset transition

How to animate the transition between datasets

picture of a mirror histogram made with react and d3.js

Mirror histogram

Create a mirror histogram to compare the distribution of 2 groups in a dataset

Picture of a histogram with small multiple built with react and d3.js

Small multiple

Create one panel per group to show its distribution separately

Picture of a histogram with multiple groups built with react and d3.js

Multiple groups

A histogram with <b>multiple</b> groups displayed on the same axis.

Picture of a boxplot with jitter built using react and d3.js

Boxplot with jitter

Add individual data points using jitter on top of the boxplot

Picture of a box component, allowing to build a boxplot later on

Boxplot shape

How to build a boxplot shape in SVG

Picture of a basic boxplot built with react and d3

Basic boxplot

How to build a basic boxplot with react

Picture of a horizontal boxplot built with react and d3

Horizontal boxplot

How to build a horizontal boxplot with react

Picture of a basic ridgeline chart built with react and d3

Basic ridgeline chart

Most basic version of a ridgeline plot

Picture of a horizontal barplot made with React and d3

Basic barplot

Most basic barplot built with React and d3

GIF of a data update on a React barplot

Barplot dataset transition

How to smoothly animate the transition between dataset

Picture of a stacked barchart made with react and d3

Horizontal Stacked Barplot

Represent group and subgroup values by stacking the data

Picture of a vertical stacked barchart made with react and d3

Vertical Stacked Barplot

Represent group and subgroup values by stacking the data

Picture of a very simple lollipop chart

Most basic lollipop plot

Learn how to build a very simple lollipop chart with React and D3.js

Picture of a very simple dumbbell chart

Most basic dumbbell plot

Learn how to build a very simple dumbbell chart with React and D3.js

Picture of a lollipop chart with hover effect

Lollipop with hover effect

Learn how to add a hover effect to your lollipop chart

Picture of a lollipop with buttons and animated transition

Animation between dataset

Learn how to build a smooth animated transition between 2 datasets

Picture of the background grid of a radar chart

Most basic line chart

Learn how to build the background grid of a radar chart

Picture of a very simple radar chart with 1 group only made with react and d3

Most basic radar chart

The most basic radar chart one can make using d3 and react

Picture of a radar chart made with react and d3, with several groups displayed on the figure.

Multi-group radar chart

Radar chart with several groups displayed

GIF of a radar chart, a line chart and a lollipop that animate between dataset

Radar chart, line chart an lollipop with animated transition

Three charts connected to same buttons, with smooth, synchronized animation when a button is clicked

Picture of a very simple line chart made with react and d3

Most basic line chart

The most basic line chart one can make using d3 and react

GIF of a line chart that animates between 2 dataset

Line chart with dataset transition

How to smoothly animate the transition between 2 dataset on a line chart

line charts with synchronized cursors

Synchronized cursors

Add a cursor synchronized on all your charts

Picture of a basic area chart made with React and D3

Basic Area Chart

Most basic version of an area chart made with react and d3.js

picture of a basic stacked area plot made with react

Basis stacked area chart

Most basic version of a stacked area chart. Explains how to use the stack() function of d3.js

Picture of a basic streamgraph made using Reacrt and d3.js

Basic Streamgraph

Most basic streamgraph one can build using d3 and react

GIF of a streamgraph react component that supports hover effect

Streamgraph with hover effect

How to add a hover effect on a streamgraph to highlight a group

GIF of a streamgraph

Offset and Smoothing transition

An interactive streamgraph example showing how to animate transition between the chart stacking features.

GIF of a streamgraph with multiple interactive features

Streamgraph application

Streamgraph with a slider to zoom on a time stamp and with interactive inline legends

Picture of a timeseries chart made with React and D3.js: scatterplot and line chart in use.

Timeseries with moving average

A scatterplot used for timeseries, with the moving average shown as a line chart on top.

Picture of a very basic circle packing chart

Most basic circular packing chart

The most basic circular packing chart one can make using d3.js and React.

Picture of a very basic circle packing chart with 2 levels of hierarchy

Circular packing: 2 levels of hierarchy

A simple circular packing chart with 2 levels of hierarchy built with React and d3.

Picture of a circle packing chart made using the d3-force plugin

Circle Pack with d3-force

Another approach to build a circle packing chart using physical forces to compute node positions.

Picture of a vertical arc diagram

Vertical arc diagram

The vertical version of the arc diagram is more convenient to display labels

Picture of a very simple network chart built with React and D3.js.

Most basic network chart

Most basic network chart using the d3-force plugin to apply physical forces.

Picture of a playground allowing to play with the various d3 forces

Play with forces

A playground to discover the effect of the various forces you can apply to your particles

Picture of a force directed network chart showing character co-occurence in les miserables

Force directed graph

A force directed network chart showing character co-occurence in les miserables

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/animation.html b/animation.html index 2d60e6a0..b04b16f3 100644 --- a/animation.html +++ b/animation.html @@ -1 +1 @@ -Animation

Animation

Dataviz logo representing a Anim chart.

Animation is both the most challenging and the most exciting part of an interactive chart. Animation is like salt: use the right amount of it and your creation is a delight. Too much of it and it spoils the dish 🀌.

There are many ways to animate the transition between 2 chart states. Here I suggest to use react-spring in combination with react andd3.js.

Useful links

Work in Progress

This section is a work in progress. 🚧

For now, it just lists all the charts using react-spring in the gallery.

But I plan to write some complete tutorials on this passionating and complicated topic. You can subscribe to the project to know when it's ready!


Subscribe


GIF of a bubble plot smoothly transitioning data

Bubble plot data set transition

How to smoothly animate the transition between dataset

gif of a violin plot smoothly transitioning to a boxplot using shape morphism

Violin to Boxplot transition

Using shape morphism to smoothly transition from a boxplot to a violin and reverse

GIF showing a violin plot with varying bucket size

Bucket size effect

Interactive example showing the bucket size effect on a violin chart

GIF showing a mirror transition between a boxplot and a violin plot

Boxplot to Violin plot

Interactive example showing the difference between a boxplot and a violin

GIF of a histogram with animated data transition

Histogram dataset transition

How to animate the transition between datasets

GIF of a data update on a React barplot

Barplot dataset transition

How to smoothly animate the transition between dataset

GIF of a line chart that animates between 2 dataset

Line chart with dataset transition

How to smoothly animate the transition between 2 dataset on a line chart

GIF of a streamgraph

Offset and Smoothing transition

An interactive streamgraph example showing how to animate transition between the chart stacking features.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +Animation

Animation

Dataviz logo representing a Anim chart.

Animation is both the most challenging and the most exciting part of an interactive chart. Animation is like salt: use the right amount of it and your creation is a delight. Too much of it and it spoils the dish 🀌.

There are many ways to animate the transition between 2 chart states. Here I suggest to use react-spring in combination with react andd3.js.

Useful links

Work in Progress

This section is a work in progress. 🚧

For now, it just lists all the charts using react-spring in the gallery.

But I plan to write some complete tutorials on this passionating and complicated topic. You can subscribe to the project to know when it's ready!


Subscribe


GIF of a bubble plot smoothly transitioning data

Bubble plot data set transition

How to smoothly animate the transition between dataset

gif of a violin plot smoothly transitioning to a boxplot using shape morphism

Violin to Boxplot transition

Using shape morphism to smoothly transition from a boxplot to a violin and reverse

GIF showing a violin plot with varying bucket size

Bucket size effect

Interactive example showing the bucket size effect on a violin chart

GIF showing a mirror transition between a boxplot and a violin plot

Boxplot to Violin plot

Interactive example showing the difference between a boxplot and a violin

GIF of a histogram with animated data transition

Histogram dataset transition

How to animate the transition between datasets

GIF of a data update on a React barplot

Barplot dataset transition

How to smoothly animate the transition between dataset

GIF of a line chart that animates between 2 dataset

Line chart with dataset transition

How to smoothly animate the transition between 2 dataset on a line chart

GIF of a streamgraph

Offset and Smoothing transition

An interactive streamgraph example showing how to animate transition between the chart stacking features.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/arc-diagram.html b/arc-diagram.html index d12dea4f..dd6b5946 100644 --- a/arc-diagram.html +++ b/arc-diagram.html @@ -1,4 +1,4 @@ -How to build an Arc Diagram with React and D3.

Arc diagram

Dataviz logo representing a Arc chart.

An arc diagram is a special kind of network graph. It is consituted by nodes that represent entities and by links that show relationships between entities. In arc diagrams, nodes are displayed along a single axis and links are represented with arcs.

This page is a step by step tutorial explaining how to build an Arc diagram component with React and D3.js. It comes with explanations and code sandboxes. It starts by simple concept like how to format the data and how to draw arcs in SVG, and then goes further with hover effect, tooltip and more.

Useful links

The Data

Two layers of information are required to build an arc diagram: a list of nodes to build the circles and a list of links to build the arcs.

Many different data structures can be used to store such information. In this tutorial I suggest to start with the following:

export const data = {
+How to build an Arc Diagram with React and D3.

Arc diagram

Dataviz logo representing a Arc chart.

An arc diagram is a special kind of network graph. It is consituted by nodes that represent entities and by links that show relationships between entities. In arc diagrams, nodes are displayed along a single axis and links are represented with arcs.

This page is a step by step tutorial explaining how to build an Arc diagram component with React and D3.js. It comes with explanations and code sandboxes. It starts by simple concept like how to format the data and how to draw arcs in SVG, and then goes further with hover effect, tooltip and more.

Useful links

The Data

Two layers of information are required to build an arc diagram: a list of nodes to build the circles and a list of links to build the arcs.

Many different data structures can be used to store such information. In this tutorial I suggest to start with the following:

export const data = {
   nodes: [
       { id: "Myriel", group: 'team1' },
       { id: "Anne", group: 'team1' },
@@ -97,4 +97,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Arc Diagram inspiration

If you're looking for inspiration to create your next Arc Diagram, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Arc Diagram looks good!

visit

Variations

Once you've understood how to build a basic arc diagram with d3 and react, it opens an infinite world of customization. Here are a few examples highlighting what it is possible to do with arc diagrams.

Click on the overview below to get details and code.


Picture of a vertical arc diagram

Vertical arc diagram

The vertical version of the arc diagram is more convenient to display labels

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Arc Diagram inspiration

If you're looking for inspiration to create your next Arc Diagram, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Arc Diagram looks good!

visit

Variations

Once you've understood how to build a basic arc diagram with d3 and react, it opens an infinite world of customization. Here are a few examples highlighting what it is possible to do with arc diagrams.

Click on the overview below to get details and code.


Picture of a vertical arc diagram

Vertical arc diagram

The vertical version of the arc diagram is more convenient to display labels

Flow

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/area-plot.html b/area-plot.html index 637eb72c..394818a6 100644 --- a/area-plot.html +++ b/area-plot.html @@ -1,4 +1,4 @@ -Area charts with React

Area charts

Dataviz logo representing a Area chart.

An area chart displays the evolution of one numeric variables. It is like a line chart, but with the area below the line being filled.

This section describes how to build area charts on the web with d3.js and react. It starts very basic and then explains how to add more complex features like brushing, adding hover effects and more.

Useful links

The Data

The dataset required to build a line chart is usually an array where each item is an object providing the x and the y values of the data point.


Here is a minimal example:

const data = [
+Area charts with React

Area charts

Dataviz logo representing a Area chart.

An area chart displays the evolution of one numeric variables. It is like a line chart, but with the area below the line being filled.

This section describes how to build area charts on the web with d3.js and react. It starts very basic and then explains how to add more complex features like brushing, adding hover effects and more.

Useful links

The Data

The dataset required to build a line chart is usually an array where each item is an object providing the x and the y values of the data point.


Here is a minimal example:

const data = [
   {x:1, y: 90},
   {x: 2, y: 12},
   {x: 3, y: 34},
@@ -13,4 +13,4 @@
   .y0(yScale(0));
 
 // call the function with the dataset
-const areaPath = areaBuilder(data);

Both a y0 and a y1 arguments are used. They provide both the bottom and the top position of the shape for each x position.

The output areaPath can now be passed to a path resulting in the following area chart:

A very basic area chart made using react and the area() function of d3.js

Area chart inspiration

If you're looking for inspiration to create your next Area chart, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Area chart looks good!

visit



Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +const areaPath = areaBuilder(data);

Both a y0 and a y1 arguments are used. They provide both the bottom and the top position of the shape for each x position.

The output areaPath can now be passed to a path resulting in the following area chart:

A very basic area chart made using react and the area() function of d3.js

Area chart inspiration

If you're looking for inspiration to create your next Area chart, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Area chart looks good!

visit



Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/articles.html b/articles.html index 849f8f29..7a314677 100644 --- a/articles.html +++ b/articles.html @@ -1 +1 @@ -How to make react and d3.js work together

Dataviz Insights with React and D3.js


While our gallery showcases a myriad of graph examples, this space is dedicated to delving into the intricacies of data visualization using React and D3.js.

From unraveling the complexities of creating stacked bar plots with negative values to envisioning futuristic visualizations, our articles aim to enlighten, inspire, and guide you through the advanced realms of dataviz.

Whether you're a seasoned developer or just starting out, these articles offer a wealth of knowledge to elevate your visualization game.

Let's embark on this enlightening journey together! πŸ”₯

πŸ” Stacked barplot: how to deal with negative values

A stacked barchart displays the values of items split in group and subgroups. It's a quite common chart type, but dealing with negative values in the dataset brings some interesting dataviz discussions.Read more

6 minutes read

The next articles are currently in writing mode. ⬇️

They will be released soon and you can be updated through my newsletter:



Using react and d3.js: The 2 strategies

React modifies the DOM. So does d3.js. It makes it notoriously hard to have them work together. This blog post describes the 2 main strategies to use d3.js in a react app, with their pros and cons.

4 minutes read

Axes: build them with react (and a bit of d3)

Most of the viz types need some axes to be insightful. This post explains how to build them from a d3 scale, using the tick() method of d3 to create re-usable react components.

8 minutes read

Responsiveness: a hook that makes your viz fits its container

Viz components often take a width and a height properties as input. This blogposts explains how to build a wrapper around it that computes the parent's div dimension and pass it as props

5 minutes read

Hover interaction

Interactivity is an important part of dataviz when working in the browser. Adding a hover effect can improve the user experience by highlighting a series on the chart. Here are a couple way to implement it, always keeping performances in mind.

6 minutes read

Graph to graph interaction

Let's say you have a choropleth map on a side, a timeseries on the other. How can you add cross-viz interactions, like hovering a country to highlight its trend on the timeseries?

10 minutes read

Spring animations with react spring

It's often necessary to transition between 2 ys of a graph. React-spring is here to help, allowing to use spring animations easily.

5 minutes read

Dataset transition

Adding a smooth transition between dataset often adds a nice touch to your viz component. Let's see how to implement it with react-spring.

5 minutes read

Shape morphism: animate the transition between 2 distincts charts

How can we build a smooth transition between a pie chart and a barplot? The flubber js library allows to interpolate shapes and react-spring can animate this interpolation.

5 minutes read

Improve chart performance with Canvas

Rendering a chart using svg is limited in term of performace. The DOM gets to crowded and updating it ends up being slow. Using canvas is the best workaround but you need to be able to draw your svg path using it!

5 minutes read

Fix the blurry canvas on Retina screens

When using canvas for your viz, the result will be blurry on retina screens if you don't scale the canvas properly. Here is why and how to implement it.

5 minutes read

What is a color

There are so many ways to define a color when talking with a computer. Let's take a tour and see what's the most appropriate for a dataviz point of view.

3 minutes read

Buiding a futuristic viz

What makes a viz look from the future. And how to implement it with d3.js and reac.

3 minutes read

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +How to make react and d3.js work together

Dataviz Insights with React and D3.js


While our gallery showcases a myriad of graph examples, this space is dedicated to delving into the intricacies of data visualization using React and D3.js.

From unraveling the complexities of creating stacked bar plots with negative values to envisioning futuristic visualizations, our articles aim to enlighten, inspire, and guide you through the advanced realms of dataviz.

Whether you're a seasoned developer or just starting out, these articles offer a wealth of knowledge to elevate your visualization game.

Let's embark on this enlightening journey together! πŸ”₯

πŸ” Stacked barplot: how to deal with negative values

A stacked barchart displays the values of items split in group and subgroups. It's a quite common chart type, but dealing with negative values in the dataset brings some interesting dataviz discussions.Read more

6 minutes read

The next articles are currently in writing mode. ⬇️

They will be released soon and you can be updated through my newsletter:



Using react and d3.js: The 2 strategies

React modifies the DOM. So does d3.js. It makes it notoriously hard to have them work together. This blog post describes the 2 main strategies to use d3.js in a react app, with their pros and cons.

4 minutes read

Axes: build them with react (and a bit of d3)

Most of the viz types need some axes to be insightful. This post explains how to build them from a d3 scale, using the tick() method of d3 to create re-usable react components.

8 minutes read

Responsiveness: a hook that makes your viz fits its container

Viz components often take a width and a height properties as input. This blogposts explains how to build a wrapper around it that computes the parent's div dimension and pass it as props

5 minutes read

Hover interaction

Interactivity is an important part of dataviz when working in the browser. Adding a hover effect can improve the user experience by highlighting a series on the chart. Here are a couple way to implement it, always keeping performances in mind.

6 minutes read

Graph to graph interaction

Let's say you have a choropleth map on a side, a timeseries on the other. How can you add cross-viz interactions, like hovering a country to highlight its trend on the timeseries?

10 minutes read

Spring animations with react spring

It's often necessary to transition between 2 ys of a graph. React-spring is here to help, allowing to use spring animations easily.

5 minutes read

Dataset transition

Adding a smooth transition between dataset often adds a nice touch to your viz component. Let's see how to implement it with react-spring.

5 minutes read

Shape morphism: animate the transition between 2 distincts charts

How can we build a smooth transition between a pie chart and a barplot? The flubber js library allows to interpolate shapes and react-spring can animate this interpolation.

5 minutes read

Improve chart performance with Canvas

Rendering a chart using svg is limited in term of performace. The DOM gets to crowded and updating it ends up being slow. Using canvas is the best workaround but you need to be able to draw your svg path using it!

5 minutes read

Fix the blurry canvas on Retina screens

When using canvas for your viz, the result will be blurry on retina screens if you don't scale the canvas properly. Here is why and how to implement it.

5 minutes read

What is a color

There are so many ways to define a color when talking with a computer. Let's take a tour and see what's the most appropriate for a dataviz point of view.

3 minutes read

Buiding a futuristic viz

What makes a viz look from the future. And how to implement it with d3.js and reac.

3 minutes read

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/barplot.html b/barplot.html index 65e23b8e..65f4a086 100644 --- a/barplot.html +++ b/barplot.html @@ -1,4 +1,4 @@ -Barplot with React

Barplot

Dataviz logo representing a Bar chart.

A barplot displays a numeric value for several groups of a dataset using rectangles. This page is a step-by-step guide on how to build your own barplot for the web, using React and D3.js.

It starts with very basic concepts like data structure, scales and svg rectangle rendering. It then shows how to add interactivity to the chart with hover effects. Last but not least it explains how to build variations like the stacked barplot.

Useful links

The Data

The dataset required to build a barplot is usually an array where each item is an object providing the name and the value of the group.


Here is a minimal example

const data = [
+Barplot with React

Barplot

Dataviz logo representing a Bar chart.

A barplot displays a numeric value for several groups of a dataset using rectangles. This page is a step-by-step guide on how to build your own barplot for the web, using React and D3.js.

It starts with very basic concepts like data structure, scales and svg rectangle rendering. It then shows how to add interactivity to the chart with hover effects. Last but not least it explains how to build variations like the stacked barplot.

Useful links

The Data

The dataset required to build a barplot is usually an array where each item is an object providing the name and the value of the group.


Here is a minimal example

const data = [
   {name:"Mark", value: 90},
   {name:"Robert", value: 12},
   {name:"Emily", value: 34},
@@ -63,4 +63,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Transition

When the dataset updates, it adds a nice touch to smoothly animate the transition. In the example below, changing the dataset will update the bar sizes and their positions on the Y axis to keep the ranking accurate.

Animation is a complicated topic in dataviz. We have to deal with updates (an element changes its features), enter (a new element appears) and exit (an element is not present anymore) patterns.

I suggest to rely on the react-spring library to help here. Please check this dedicated blogpost to get explanations about the code of this example.

Most basic barplot built with d3.js for scales, and react for rendering

Stacking

A stacked barplot is a variation of a barplot where an additional level of grouping is represented. Each bar represent the value of a group, for instance how much each my friend spent in the last month. Each bar is then subdivided, each part representing the value of a subgroup, for instance the category of expense.

D3 comes with a very handy stack() function. The 2 tutorials below explain how this function works, and how to use it to render a clean stacked barplot.

Picture of a stacked barchart made with react and d3

Horizontal Stacked Barplot

Represent group and subgroup values by stacking the data

Picture of a vertical stacked barchart made with react and d3

Vertical Stacked Barplot

Represent group and subgroup values by stacking the data

Vertical barplot

The vertical option is less common since it makes is much harder to read the labels. But if you really need it, it is just a matter of swaping the X and Y axes of the previous example.

This example will be publish soon, please subscribe below if you want to be notified.

Hover effect

This example will be publish soon, please subscribe to the newsletter if you want to be notified.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Transition

When the dataset updates, it adds a nice touch to smoothly animate the transition. In the example below, changing the dataset will update the bar sizes and their positions on the Y axis to keep the ranking accurate.

Animation is a complicated topic in dataviz. We have to deal with updates (an element changes its features), enter (a new element appears) and exit (an element is not present anymore) patterns.

I suggest to rely on the react-spring library to help here. Please check this dedicated blogpost to get explanations about the code of this example.

Most basic barplot built with d3.js for scales, and react for rendering

Stacking

A stacked barplot is a variation of a barplot where an additional level of grouping is represented. Each bar represent the value of a group, for instance how much each my friend spent in the last month. Each bar is then subdivided, each part representing the value of a subgroup, for instance the category of expense.

D3 comes with a very handy stack() function. The 2 tutorials below explain how this function works, and how to use it to render a clean stacked barplot.

Picture of a stacked barchart made with react and d3

Horizontal Stacked Barplot

Represent group and subgroup values by stacking the data

Picture of a vertical stacked barchart made with react and d3

Vertical Stacked Barplot

Represent group and subgroup values by stacking the data

Vertical barplot

The vertical option is less common since it makes is much harder to read the labels. But if you really need it, it is just a matter of swaping the X and Y axes of the previous example.

This example will be publish soon, please subscribe below if you want to be notified.

Hover effect

This example will be publish soon, please subscribe to the newsletter if you want to be notified.

Ranking

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/boxplot.html b/boxplot.html index 08f85ece..0b170a13 100644 --- a/boxplot.html +++ b/boxplot.html @@ -1,4 +1,4 @@ -Boxplot with React

Boxplot

Dataviz logo representing a Box1 chart.

A boxplot summarizes the distribution of a numeric variable, often for several groups of a dataset. This page is a step-by-step guide on how to build a reusable boxplot component for the web using React and D3.js.

It starts by describing how to format the dataset and how to initialize the boxplot component. It then explains how to create a Box component that displays a single box. Finally, it shows how to render the boxplot and suggests a few variations. πŸ™‡β€β™‚οΈ.

Useful links

The Data πŸ’Ύ

The dataset used to build a boxplot is usually an array of objects. For each object, a name property provides the group name, and a value property provides the numeric value. It looks like this:

const data = [
+Boxplot with React

Boxplot

Dataviz logo representing a Box1 chart.

A boxplot summarizes the distribution of a numeric variable, often for several groups of a dataset. This page is a step-by-step guide on how to build a reusable boxplot component for the web using React and D3.js.

It starts by describing how to format the dataset and how to initialize the boxplot component. It then explains how to create a Box component that displays a single box. Finally, it shows how to render the boxplot and suggests a few variations. πŸ™‡β€β™‚οΈ.

Useful links

The Data πŸ’Ύ

The dataset used to build a boxplot is usually an array of objects. For each object, a name property provides the group name, and a value property provides the numeric value. It looks like this:

const data = [
   { name: "A", value: 10.7577 },
   { name: "A", value: 19.9273 },
   { name: "B", value: 13.8917 },
@@ -187,4 +187,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Boxplot inspiration

If you're looking for inspiration to create your next Boxplot, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Boxplot looks good!

visit

Boxplot variations

Even if powerful to summarize the distribution of a numeric variable, the boxplot has flaws.

It indeed hides the underlying distribution. For instance, a low sample size or a bi-modal distribution is impossible to detect by reading the boxes only.

Jittering is a good workaround. Add all individual data points with low size, low opacity, and some random shift to the right or the left (jitter). The underlying distribution becomes instantly available.

Note that another good alternative is the violin plot, especially for a high sample size.

gif of a violin plot smoothly transitioning to a boxplot using shape morphism

Violin to Boxplot transition

Using shape morphism to smoothly transition from a boxplot to a violin and reverse

Picture of a violin plot with variable bucket size

Violin with variable bucket size

A violin plot with a slider to change the bucket size in use

Picture of a boxplot with jitter built using react and d3.js

Boxplot with jitter

Add individual data points using jitter on top of the boxplot

Picture of a horizontal boxplot built with react and d3

Horizontal boxplot

How to build a horizontal boxplot with react

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Boxplot inspiration

If you're looking for inspiration to create your next Boxplot, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Boxplot looks good!

visit

Boxplot variations

Even if powerful to summarize the distribution of a numeric variable, the boxplot has flaws.

It indeed hides the underlying distribution. For instance, a low sample size or a bi-modal distribution is impossible to detect by reading the boxes only.

Jittering is a good workaround. Add all individual data points with low size, low opacity, and some random shift to the right or the left (jitter). The underlying distribution becomes instantly available.

Note that another good alternative is the violin plot, especially for a high sample size.

gif of a violin plot smoothly transitioning to a boxplot using shape morphism

Violin to Boxplot transition

Using shape morphism to smoothly transition from a boxplot to a violin and reverse

Picture of a violin plot with variable bucket size

Violin with variable bucket size

A violin plot with a slider to change the bucket size in use

Picture of a boxplot with jitter built using react and d3.js

Boxplot with jitter

Add individual data points using jitter on top of the boxplot

Picture of a horizontal boxplot built with react and d3

Horizontal boxplot

How to build a horizontal boxplot with react

Distribution

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/bubble-map.html b/bubble-map.html index 318954c4..2b77ae98 100644 --- a/bubble-map.html +++ b/bubble-map.html @@ -1,4 +1,4 @@ -How to build a bubble map component with React and D3.

Bubble Map

Dataviz logo representing a BubbleMap chart.

A bubble map uses circles of different size to represent a numeric value on a territory. It displays one bubble per geographic coordinate, or one bubble per region.

This page explains how to build bubble maps for the web using d3.js and react. Several tools can be used to display the background map as shown in the dedicated section. Circles are then computed with d3 and render using SVG or canvas elements with react.

Examples start easy and add layers of complexity progressively. You will always find explanations and code sandboxes for each step.

Useful links

The Data

Two pieces of information are required to build a bubble map:

β†’ Geographic information

The first thing you need is the 2d coordinates of the boundaries of the regions you want to represent. If you are trying to build a world map, you need to know where the country boundaries are located πŸ€·β€β™€οΈ.

Several formats exist to store such a piece of information. When working with d3.js, the expected format is geoJSON. A geoJSON file looks pretty much like this:


{
+How to build a bubble map component with React and D3.

Bubble Map

Dataviz logo representing a BubbleMap chart.

A bubble map uses circles of different size to represent a numeric value on a territory. It displays one bubble per geographic coordinate, or one bubble per region.

This page explains how to build bubble maps for the web using d3.js and react. Several tools can be used to display the background map as shown in the dedicated section. Circles are then computed with d3 and render using SVG or canvas elements with react.

Examples start easy and add layers of complexity progressively. You will always find explanations and code sandboxes for each step.

Useful links

The Data

Two pieces of information are required to build a bubble map:

β†’ Geographic information

The first thing you need is the 2d coordinates of the boundaries of the regions you want to represent. If you are trying to build a world map, you need to know where the country boundaries are located πŸ€·β€β™€οΈ.

Several formats exist to store such a piece of information. When working with d3.js, the expected format is geoJSON. A geoJSON file looks pretty much like this:


{
   "type": "FeatureCollection",
   "features": [
     {
@@ -154,4 +154,4 @@
       strokeWidth={1}
     />
   );
-};

A bubble chart component that smoothly animates changes between datasets.

Animation in dataviz using React is a big topic. It's impossible to go in-depth here! I will publish a dedicated blog post on the topic soon. Please subscribe to the newsletter if you want to be notified.

Bubble inspiration

If you're looking for inspiration to create your next Bubble, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Bubble looks good!

visit

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +};

A bubble chart component that smoothly animates changes between datasets.

Animation in dataviz using React is a big topic. It's impossible to go in-depth here! I will publish a dedicated blog post on the topic soon. Please subscribe to the newsletter if you want to be notified.

Bubble inspiration

If you're looking for inspiration to create your next Bubble, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Bubble looks good!

visit

Map

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/bubble-plot.html b/bubble-plot.html index 252a16a2..4575db94 100644 --- a/bubble-plot.html +++ b/bubble-plot.html @@ -1,4 +1,4 @@ -Bubble plot with React

Bubble plot

Dataviz logo representing a BubblePlot chart.

A bubble plot is an extension of a scatterplot, where each circle has its size proportional to a numeric value. This page is a step-by-step guide on how to build your own bubble chart for the web, using React and D3.js.

This page focuses on the implementation of features that are different from the scatterplot that has its dedicated section. It describes how the dataset differs, how the circle size can be mapped to a numeric value, and how to explicit it using a legend. Last but not least it explains how to add interactivity: hover effect, tooltip, and dataset transition. πŸ™‡β€β™‚οΈ.

Useful links

The Data

The dataset used to build a bubble plot is usually an array of objects where each object is a data point. For each object, at least 3 properties are required.

Two properties are used for the X and Y axis, the third one is used for the circle size.

Note that you can add more properties to the object. For instance, a name can be displayed in the tooltip, and a group can be used to color the bubbles.

const data = [
+Bubble plot with React

Bubble plot

Dataviz logo representing a BubblePlot chart.

A bubble plot is an extension of a scatterplot, where each circle has its size proportional to a numeric value. This page is a step-by-step guide on how to build your own bubble chart for the web, using React and D3.js.

This page focuses on the implementation of features that are different from the scatterplot that has its dedicated section. It describes how the dataset differs, how the circle size can be mapped to a numeric value, and how to explicit it using a legend. Last but not least it explains how to add interactivity: hover effect, tooltip, and dataset transition. πŸ™‡β€β™‚οΈ.

Useful links

The Data

The dataset used to build a bubble plot is usually an array of objects where each object is a data point. For each object, at least 3 properties are required.

Two properties are used for the X and Y axis, the third one is used for the circle size.

Note that you can add more properties to the object. For instance, a name can be displayed in the tooltip, and a group can be used to color the bubbles.

const data = [
   {
     "x": 43.828,
     "y": 31889923,
@@ -106,4 +106,4 @@
       strokeWidth={1}
     />
   );
-};
30405060708090

A bubble chart component that smoothly animates changes between datasets.

Animation in dataviz using React is a big topic. It's impossible to go in-depth here! I will publish a dedicated blog post on the topic soon. Please subscribe to the newsletter if you want to be notified.

Real-life application

Let's apply the concepts learned above to a real-life example.

I like this scatterplot originally published on the data wrapper blog. It shows a strong correlation between vulnerability to climate change and CO2 emissions.


The chart has several features that are interesting to reproduce from a technical point of view:

  • Custom annotation: only a fraction of the country names are written
  • Hover effect: the hovered country is highlighted with a black stroke. After a short delay, countries of other groups are dimmed. Note that the effect is triggered once the mouse approaches the marker, no need to be perfectly on top.
  • Tooltip: highly customized and linked to the mouse position

The countries with the highest vulnerability to climate change have the lowest CO2 emissions

All countries sorted by their vulnerability and readiness to climate change. The size shows the CO2 emission per person in that country.

High Readiness↑Low Readiness↓QatarBahrainU.S.Trinidad and TobagoCzech RepublicSingaporeNorwayIndiaSudanChadSomalia

Reproduction of a chart originally published by Data Wrapper using react and d3.js.

Variations

Once you've understood how to build a basic bubble chart with d3 and react, it opens an infinite world of customization. Here are a few examples using the same concepts.

Click on the overview below to get details and code.


Picture of a circle packing chart made using the d3-force plugin

Circle Pack with d3-force

Another approach to build a circle packing chart using physical forces to compute node positions.



Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +};
30405060708090

A bubble chart component that smoothly animates changes between datasets.

Animation in dataviz using React is a big topic. It's impossible to go in-depth here! I will publish a dedicated blog post on the topic soon. Please subscribe to the newsletter if you want to be notified.

Real-life application

Let's apply the concepts learned above to a real-life example.

I like this scatterplot originally published on the data wrapper blog. It shows a strong correlation between vulnerability to climate change and CO2 emissions.


The chart has several features that are interesting to reproduce from a technical point of view:

  • Custom annotation: only a fraction of the country names are written
  • Hover effect: the hovered country is highlighted with a black stroke. After a short delay, countries of other groups are dimmed. Note that the effect is triggered once the mouse approaches the marker, no need to be perfectly on top.
  • Tooltip: highly customized and linked to the mouse position

The countries with the highest vulnerability to climate change have the lowest CO2 emissions

All countries sorted by their vulnerability and readiness to climate change. The size shows the CO2 emission per person in that country.

High Readiness↑Low Readiness↓QatarBahrainU.S.Trinidad and TobagoCzech RepublicSingaporeNorwayIndiaSudanChadSomalia

Reproduction of a chart originally published by Data Wrapper using react and d3.js.

Variations

Once you've understood how to build a basic bubble chart with d3 and react, it opens an infinite world of customization. Here are a few examples using the same concepts.

Click on the overview below to get details and code.


Picture of a circle packing chart made using the d3-force plugin

Circle Pack with d3-force

Another approach to build a circle packing chart using physical forces to compute node positions.



Correlation

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/build-axis-with-react.html b/build-axis-with-react.html index eea9b7b4..a7575316 100644 --- a/build-axis-with-react.html +++ b/build-axis-with-react.html @@ -1,4 +1,4 @@ -Building graph axes with React (and d3.js)

Building graph axes with React (and d3.js)


This post explains how to build axes from d3 scales for a chart. It relies on the tick() method to compute the tick positions and use react for the rendering. The code of the BottomAxis and LeftAxiscomponents is provided, together with some reproducible examples.

This minimal example uses scaleLinear() to compute the scales, ticks() to compute tick positions and react to render the axes.

-Building a bottom axis with React

The code snippet below builds a AxisBottom component. It is very much inspired from this blogpost by Amelia Wattenberger. I've just changed a few things, notably passing a scale as input instead of a range and a domain.

The logic mainly relies on the ticks() method of a d3 scale. It takes a target number of ticks as input, find the most appropriate way to build smart ticks based on this target, and returns an array with all the tick positions.

What follows is just some svg drawings based on those tick positions.

const TICK_LENGTH = 6;
+Building graph axes with React (and d3.js)

Building graph axes with React (and d3.js)


This post explains how to build axes from d3 scales for a chart. It relies on the tick() method to compute the tick positions and use react for the rendering. The code of the BottomAxis and LeftAxiscomponents is provided, together with some reproducible examples.

This minimal example uses scaleLinear() to compute the scales, ticks() to compute tick positions and react to render the axes.

-Building a bottom axis with React

The code snippet below builds a AxisBottom component. It is very much inspired from this blogpost by Amelia Wattenberger. I've just changed a few things, notably passing a scale as input instead of a range and a domain.

The logic mainly relies on the ticks() method of a d3 scale. It takes a target number of ticks as input, find the most appropriate way to build smart ticks based on this target, and returns an array with all the tick positions.

What follows is just some svg drawings based on those tick positions.

const TICK_LENGTH = 6;
 
 export const AxisBottom = ({ xScale, pixelsPerTick }) => {
   const range = xScale.range();
@@ -82,4 +82,4 @@
       ))}
     </>
   );
-};

-Dealing with margins

The bottom and left axes are not displays at the border of the main chart component. Some margins are computed by the viz component. It is important to understand that a chart is composed by:

  • the global chart area, often specified by the width and height properties of the chart components.
  • the "bounds" area, i.e. the area located inside the x and y axis. It is calculated by substracting the margins

-Use the axes

Once you have the bottom and left axis component described above you just need to call them properly. You need to compute the bounds area by substracting the margins to the total svg area.

Don't forget to add an additional translation to the bottom axis to render it... at the bottom.

0246810

This axis is rendered without using d3.js to render.

-Alternative: the d3 way

If you're a d3.js afficionados and want to deal with as little react as possible, you can still use the good old axisBottom() and axisLeft() methods of d3 and wrap them in auseEffect() hook.

Here is an example below:

This axis is rendered using d3. The d3 necessary functions are called from a useEffect




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +};

-Dealing with margins

The bottom and left axes are not displays at the border of the main chart component. Some margins are computed by the viz component. It is important to understand that a chart is composed by:

  • the global chart area, often specified by the width and height properties of the chart components.
  • the "bounds" area, i.e. the area located inside the x and y axis. It is calculated by substracting the margins

-Use the axes

Once you have the bottom and left axis component described above you just need to call them properly. You need to compute the bounds area by substracting the margins to the total svg area.

Don't forget to add an additional translation to the bottom axis to render it... at the bottom.

0246810

This axis is rendered without using d3.js to render.

-Alternative: the d3 way

If you're a d3.js afficionados and want to deal with as little react as possible, you can still use the good old axisBottom() and axisLeft() methods of d3 and wrap them in auseEffect() hook.

Here is an example below:

This axis is rendered using d3. The d3 necessary functions are called from a useEffect




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/cartogram.html b/cartogram.html index 5f685916..0fae06ee 100644 --- a/cartogram.html +++ b/cartogram.html @@ -1 +1 @@ -How to build a cartogram with React and D3.

Cartogram

Dataviz logo representing a Cartogram chart.

A cartogram is a map in which the geometry of regions is distorted in order to convey the information of an alternate variable.

It is possible to build a Cartogram react component thanks to a js library called topogram. This page provides step-by-step explanations on how to use the library based on a geoJson file with the help of d3.js for manipulating such a data source.

Useful links

The Data

Probably uses the same as for a choropleth map or for a bubble map.

The Topogram library

As far as I can tell the best way to create a cartogram in JS is the topogram library.

However it looks like there is no easy way to install it using npm. The easiest way is probably to clone the repo and create the build, or to copy the content of the cartogram.js file.

ToDoAdd example of usage of the topogram lib

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +How to build a cartogram with React and D3.

Cartogram

Dataviz logo representing a Cartogram chart.

A cartogram is a map in which the geometry of regions is distorted in order to convey the information of an alternate variable.

It is possible to build a Cartogram react component thanks to a js library called topogram. This page provides step-by-step explanations on how to use the library based on a geoJson file with the help of d3.js for manipulating such a data source.

Useful links

The Data

Probably uses the same as for a choropleth map or for a bubble map.

The Topogram library

As far as I can tell the best way to create a cartogram in JS is the topogram library.

However it looks like there is no easy way to install it using npm. The easiest way is probably to clone the repo and create the build, or to copy the content of the cartogram.js file.

ToDoAdd example of usage of the topogram lib

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/chord-diagram.html b/chord-diagram.html index b01210cc..dcd71a69 100644 --- a/chord-diagram.html +++ b/chord-diagram.html @@ -1,4 +1,4 @@ -How to build a chord diagram with React and D3.

Chord diagram

Dataviz logo representing a Chord chart.

A chord diagram represents flows between several entities called nodes. Each node is represented by a fragment on the outer part of the circular layout. Then, arcs are drawn between each entities. The size of the arc is proportional to the importance of the flow..

Building a chord diagram with React and D3.js relies on the d3-chord module that computes the node and arc positions for us. React can then be used to draw everything in SVG. This page is a step by step tutorial with code sandboxes. It will teach you how to build a ChordDiagram component.

Useful links

The Data

The dataset required to build a chord diagram is a square matrix. It has a dimension of n x n where n is the number of nodes.

In javascript, this matrix is represented as an array of n array. Each individual array also has n items. The matrix of flow has a direction: the second item of the third row gives the flow from element 2 to element 3.

Usually an additional array is provided, giving the name of each node.


Here is a minimal example of the data structure:

// matrix of flow
+How to build a chord diagram with React and D3.

Chord diagram

Dataviz logo representing a Chord chart.

A chord diagram represents flows between several entities called nodes. Each node is represented by a fragment on the outer part of the circular layout. Then, arcs are drawn between each entities. The size of the arc is proportional to the importance of the flow..

Building a chord diagram with React and D3.js relies on the d3-chord module that computes the node and arc positions for us. React can then be used to draw everything in SVG. This page is a step by step tutorial with code sandboxes. It will teach you how to build a ChordDiagram component.

Useful links

The Data

The dataset required to build a chord diagram is a square matrix. It has a dimension of n x n where n is the number of nodes.

In javascript, this matrix is represented as an array of n array. Each individual array also has n items. The matrix of flow has a direction: the second item of the third row gives the flow from element 2 to element 3.

Usually an additional array is provided, giving the name of each node.


Here is a minimal example of the data structure:

// matrix of flow
 const data = [
   [11975,  0, 8916, 2868],
   [ 1951, 10048, 2060, 6171],
@@ -76,4 +76,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Chord Diagram inspiration

If you're looking for inspiration to create your next Chord Diagram, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Chord Diagram looks good!

visit

First chord diagram

I suggest 2 improvements to get a descent chord diagram:

β†’ Colors

Pretty straightforward to implement. You just need to create an array of colors. Then, for each item to draw the index is always available. It can be used to retrieve the color in the color array.

β†’ Labels

A new prop needs to be passed to the component with a list of names for the nodes. I suggest to position labels as for a donut chart but many other possibilities are available.

Connections between nodes are drawn thanks to the ribbon() function of d3.js.

ToDoAdd section on hover effect
ToDoTalk about chordDirected() and chordTranspose()

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Chord Diagram inspiration

If you're looking for inspiration to create your next Chord Diagram, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Chord Diagram looks good!

visit

First chord diagram

I suggest 2 improvements to get a descent chord diagram:

β†’ Colors

Pretty straightforward to implement. You just need to create an array of colors. Then, for each item to draw the index is always available. It can be used to retrieve the color in the color array.

β†’ Labels

A new prop needs to be passed to the component with a list of names for the nodes. I suggest to position labels as for a donut chart but many other possibilities are available.

Connections between nodes are drawn thanks to the ribbon() function of d3.js.

ToDoAdd section on hover effect
ToDoTalk about chordDirected() and chordTranspose()

Flow

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/choropleth-map.html b/choropleth-map.html index 7124e24f..409b00dc 100644 --- a/choropleth-map.html +++ b/choropleth-map.html @@ -1,4 +1,4 @@ -Building Choropleth Maps with React and D3.js: A Step-by-Step Tutorial

Choropleth Map

Dataviz logo representing a Choropleth chart.

A choropleth map displays divided geographical areas or regions that are coloured in relation to a numeric variable. It enables the study of how a variable evolves across a geographical area.

Once you understood how to draw a map background from a geoJson file, it is just a matter of coloring each region with the appropriate color. On top of this, it is advised to add a color legend and some interactivity (hover effect and tooltip).

This webpage is a tutorial coming with explanation and code sandboxes. It explains how to build interactive choropleth map with React and D3.js.

Useful links

The Data

Two pieces of information are required to build a choropleth map:

β†’ Geographic information

The first thing you need to build a choropleth map is the 2d coordinates of the boundaries of the regions you want to represent. If you are trying to build a world map, you need to know where the country boundaries are located πŸ€·β€β™€οΈ.

Several formats exist to store such a piece of information. When working with d3.js, the expected format is geoJSON. A geoJSON file looks pretty much like this:


{
+Building Choropleth Maps with React and D3.js: A Step-by-Step Tutorial

Choropleth Map

Dataviz logo representing a Choropleth chart.

A choropleth map displays divided geographical areas or regions that are coloured in relation to a numeric variable. It enables the study of how a variable evolves across a geographical area.

Once you understood how to draw a map background from a geoJson file, it is just a matter of coloring each region with the appropriate color. On top of this, it is advised to add a color legend and some interactivity (hover effect and tooltip).

This webpage is a tutorial coming with explanation and code sandboxes. It explains how to build interactive choropleth map with React and D3.js.

Useful links

The Data

Two pieces of information are required to build a choropleth map:

β†’ Geographic information

The first thing you need to build a choropleth map is the 2d coordinates of the boundaries of the regions you want to represent. If you are trying to build a world map, you need to know where the country boundaries are located πŸ€·β€β™€οΈ.

Several formats exist to store such a piece of information. When working with d3.js, the expected format is geoJSON. A geoJSON file looks pretty much like this:


{
   "type": "FeatureCollection",
   "features": [
     {
@@ -85,4 +85,4 @@
     context.fillStyle = colorScale((max * i) / width); // max is the last value of the domain of the color scale
     context.fillRect(i, 0, 1, height);
   }
-}, [width, height, colorScale]);

Then you probably want to add some ticks on top of the color graduation to make it insightful.

Fortunately, the d3 linearScale comes with a handy tick() function. Basically, calling xScale.ticks(4) will create an array with approximately 4 items, each providing everything you need to draw a smartly located tick.

Color Legend is a big topic. There is much more to say about it and I'll post a complete blog post on the topic soon. Subscribe to the gallery if interested!

ToDoHover effect section
ToDoTalk more about color scale. Hover effect linked with color scale
ToDoCanvas version. Add tooltip.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}, [width, height, colorScale]);

Then you probably want to add some ticks on top of the color graduation to make it insightful.

Fortunately, the d3 linearScale comes with a handy tick() function. Basically, calling xScale.ticks(4) will create an array with approximately 4 items, each providing everything you need to draw a smartly located tick.

Color Legend is a big topic. There is much more to say about it and I'll post a complete blog post on the topic soon. Subscribe to the gallery if interested!

ToDoHover effect section
ToDoTalk more about color scale. Hover effect linked with color scale
ToDoCanvas version. Add tooltip.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/circular-barplot.html b/circular-barplot.html index 813b5f2e..cb6d8db5 100644 --- a/circular-barplot.html +++ b/circular-barplot.html @@ -1,4 +1,4 @@ -Circular Barplot with React

Circular Barplot

Dataviz logo representing a CircularBarplot chart.

A circular barplot is a variation of a barplot where bars are displayed around a circle using polar coordinates. It is a less accurate representation of the data, but provides a strong eye-catching effect.

This page describes how to deal with radial coordinates with d3.js and react to build a circular barplot. It's a step by step tutorial with several interactive sandboxes.

Useful links

The Data

The dataset required to build a circular barplot is usually an array where each item is an object providing the name and the value of the group.


Here is a minimal example

const data = [
+Circular Barplot with React

Circular Barplot

Dataviz logo representing a CircularBarplot chart.

A circular barplot is a variation of a barplot where bars are displayed around a circle using polar coordinates. It is a less accurate representation of the data, but provides a strong eye-catching effect.

This page describes how to deal with radial coordinates with d3.js and react to build a circular barplot. It's a step by step tutorial with several interactive sandboxes.

Useful links

The Data

The dataset required to build a circular barplot is usually an array where each item is an object providing the name and the value of the group.


Here is a minimal example

const data = [
   {name:"Mark", value: 90},
   {name:"Robert", value: 12},
   {name:"Emily", value: 34},
@@ -41,4 +41,4 @@
     startAngle: xScale(group.name),
     endAngle: xScale(group.name) + xScale.bandwidth(),
   });
-})

β†’ Rendering

Not much to add. Just include the paths in a svg element. Remember that 0,0 is the center of the chart instead of being the top-left corner. So we need to apply a translate at some point.

Most basic circular barplot built with d3.js and react, using radial coordinates and path instead of rect.

That's a good start but it looks pretty much like a snail so far. Let's make it a real chart with labels and values.

Labels

It is necessary to add a text element to show the name of each bar.

We need those labels to be readable (like not written upside down). So a bit of logic is necessary to determine wether or not a label must be flipped, and how to position it properly.

To do so it is necessary to switch from radians (use for the xScale) to degrees (used for the transform property).

Please check the code below for full explanation.

RemiJeanNinaNicolasLucasMarkLeaneMelanieMarionEmilyMelTiboBalkisGabrielSophieRobertPaul

Add some labels to each bar of the circular barchart to make it insightful

Circular Barplot inspiration

If you're looking for inspiration to create your next Circular Barplot, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Circular Barplot looks good!

visit

Stacking

Stacking is a process where a chart is broken up across more than one categoric variables which make up the whole.

d3 comes with some handy functions for stacking. The process is extensively described in this stacked barplot tutorial. There is nothing really different to make it circular and here is a working sandbox to discover the code.

TaylorAllisonVanessaKatelynHannahGraceStephanieSydneyCourtneyHaileyMaryErinJasmineEmmaAlyssaJessicaDanielleJordanAlexisDestinyMariaVictoriaAshleyMadisonSamanthaMichelleBaileyMorganSophiaElizabethOliviaNicoleSaraShelbyRachelCarolineSavannahLaurenIsabellaKimberlyChloeSierraPaigeMakaylaFaithAnnaSarahAndreaJennaMackenzieBriannaBrookeJenniferMeganAmberAlexandraKaitlynBrittanyKatherineKaylaRebeccaAmandaJuliaMadelineAbigailEmilyJacquelineGabrielleNatalieHaley

Add some labels to each bar of the circular barchart to make it insightful



Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +})

β†’ Rendering

Not much to add. Just include the paths in a svg element. Remember that 0,0 is the center of the chart instead of being the top-left corner. So we need to apply a translate at some point.

Most basic circular barplot built with d3.js and react, using radial coordinates and path instead of rect.

That's a good start but it looks pretty much like a snail so far. Let's make it a real chart with labels and values.

Labels

It is necessary to add a text element to show the name of each bar.

We need those labels to be readable (like not written upside down). So a bit of logic is necessary to determine wether or not a label must be flipped, and how to position it properly.

To do so it is necessary to switch from radians (use for the xScale) to degrees (used for the transform property).

Please check the code below for full explanation.

RemiJeanNinaNicolasLucasMarkLeaneMelanieMarionEmilyMelTiboBalkisGabrielSophieRobertPaul

Add some labels to each bar of the circular barchart to make it insightful

Circular Barplot inspiration

If you're looking for inspiration to create your next Circular Barplot, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Circular Barplot looks good!

visit

Stacking

Stacking is a process where a chart is broken up across more than one categoric variables which make up the whole.

d3 comes with some handy functions for stacking. The process is extensively described in this stacked barplot tutorial. There is nothing really different to make it circular and here is a working sandbox to discover the code.

MadelinePaigeElizabethLaurenAnnaTaylorJacquelineOliviaNatalieJenniferJuliaDanielleAlexisMadisonMackenzieHaileyBriannaRachelHannahMakaylaAbigailSavannahMorganVanessaSierraNicoleMichelleStephanieFaithShelbyEmmaAmandaAndreaIsabellaKaylaGabrielleSydneyKatelynChloeJessicaKimberlyJennaCourtneyAlexandraSamanthaKaitlynMeganBrittanyMaryDestinyAllisonJasmineAmberVictoriaBrookeSophiaJordanHaleySarahBaileyCarolineAshleyRebeccaGraceSaraAlyssaMariaErinKatherineEmily

Add some labels to each bar of the circular barchart to make it insightful



Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/circular-packing.html b/circular-packing.html index 44235f31..308f4d45 100644 --- a/circular-packing.html +++ b/circular-packing.html @@ -1,4 +1,4 @@ -Circular Packing chart with React

Circular Packing

Dataviz logo representing a CircularPacking chart.

A circular packing chart displays a hierarchical dataset as a set of nested circles, each circle representing a node of the data structure. Size is usually proportional to a numeric variable.

This page is a tutorial teaching how to create a circle pack chart with d3.js and React. It starts with a very basic version, adds some levels of nesting and finishes with usual customization like animating the transition between datasets.

Useful links

The Data

The dataset describes a hierarchy using a recursive structure. It is similar to a dendrogram or to a treemap.

Each item in this structure is called a node, the lowest nodes of the hierarchy being called leaves. The dataset is an object that has at least 3 properties: name, value and children. Children is an array of nodes that have this structure too.


Here is a minimal example of the data structure:

const data = {
+Circular Packing chart with React

Circular Packing

Dataviz logo representing a CircularPacking chart.

A circular packing chart displays a hierarchical dataset as a set of nested circles, each circle representing a node of the data structure. Size is usually proportional to a numeric variable.

This page is a tutorial teaching how to create a circle pack chart with d3.js and React. It starts with a very basic version, adds some levels of nesting and finishes with usual customization like animating the transition between datasets.

Useful links

The Data

The dataset describes a hierarchy using a recursive structure. It is similar to a dendrogram or to a treemap.

Each item in this structure is called a node, the lowest nodes of the hierarchy being called leaves. The dataset is an object that has at least 3 properties: name, value and children. Children is an array of nodes that have this structure too.


Here is a minimal example of the data structure:

const data = {
   type: 'node',
   name: "boss",
   value: 2300,
@@ -52,4 +52,4 @@
       cy={animatedProps.cy}
     />
   );
-}

This component uses the useSpring hook of react spring to interpolate the cx, cy and r properties. Those values are passed to a special svg element (animated.circle) that does the animation.

Animating the transition between 2 similar dataset with react and d3.js (for rendering) and react spring (for animation).

Animation in dataviz using React is a big topic. It's impossible to go in depth here! I will publish a dedicated blog post on the topic soon. Please subscribe to the newsletter if you want to be notified.

Subscribe



ToDoZoom on next level of hierarchy
ToDoWrite label along circle with curve
ToDoBetter dataset transition where circle keep position

Variations

Once you've understood how to build a basic circular packing with d3 and react, it opens an infinite world of customization. Here are a few examples using the same concepts.

Click on the overview below to get details and code.


Picture of a circle packing chart made using the d3-force plugin

Circle Pack with d3-force

Another approach to build a circle packing chart using physical forces to compute node positions.



Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

This component uses the useSpring hook of react spring to interpolate the cx, cy and r properties. Those values are passed to a special svg element (animated.circle) that does the animation.

Animating the transition between 2 similar dataset with react and d3.js (for rendering) and react spring (for animation).

Animation in dataviz using React is a big topic. It's impossible to go in depth here! I will publish a dedicated blog post on the topic soon. Please subscribe to the newsletter if you want to be notified.

Subscribe



ToDoZoom on next level of hierarchy
ToDoWrite label along circle with curve
ToDoBetter dataset transition where circle keep position

Variations

Once you've understood how to build a basic circular packing with d3 and react, it opens an infinite world of customization. Here are a few examples using the same concepts.

Click on the overview below to get details and code.


Picture of a circle packing chart made using the d3-force plugin

Circle Pack with d3-force

Another approach to build a circle packing chart using physical forces to compute node positions.



Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/connected-scatter-plot.html b/connected-scatter-plot.html index 5a4b795e..9d40c79a 100644 --- a/connected-scatter-plot.html +++ b/connected-scatter-plot.html @@ -1,4 +1,4 @@ -Connected scatterplot with React and D3.js

Connected Scatterplot

Dataviz logo representing a ScatterConnected chart.

A connected scatterplot displays the evolution of a numeric variable. Data points are represented by a dot and connected with straight line segments. A variation of the connected scatterplot allows to study the evolution of 2 numeric variables together.

This page explains how to build a connected scatterplot using react andd3.js. It is highly connected with the line chart section of the gallery but provides further information concerning connected scatterplot specific features.

Useful links

The Data

The dataset required to build a connected scatterplot is the same as for a line chart. It is usually an array where each item is an object providing the x and the y values of the data point.


Here is a minimal example:

const data = [
+Connected scatterplot with React and D3.js

Connected Scatterplot

Dataviz logo representing a ScatterConnected chart.

A connected scatterplot displays the evolution of a numeric variable. Data points are represented by a dot and connected with straight line segments. A variation of the connected scatterplot allows to study the evolution of 2 numeric variables together.

This page explains how to build a connected scatterplot using react andd3.js. It is highly connected with the line chart section of the gallery but provides further information concerning connected scatterplot specific features.

Useful links

The Data

The dataset required to build a connected scatterplot is the same as for a line chart. It is usually an array where each item is an object providing the x and the y values of the data point.


Here is a minimal example:

const data = [
   {x:1, y: 90},
   {x: 2, y: 12},
   {x: 3, y: 34},
@@ -51,4 +51,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




ToDoadd links to line chart examples
ToDoreproduce the connected scatter from the state of JS survey

Connected Scatter inspiration

If you're looking for inspiration to create your next Connected Scatter, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Connected Scatter looks good!

visit

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




ToDoadd links to line chart examples
ToDoreproduce the connected scatter from the state of JS survey

Connected Scatter inspiration

If you're looking for inspiration to create your next Connected Scatter, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Connected Scatter looks good!

visit

Evolution

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/connection-map.html b/connection-map.html index a2cdc902..6bc0c99b 100644 --- a/connection-map.html +++ b/connection-map.html @@ -1,4 +1,4 @@ -How to build a connection map component with React and D3.

Connection Map

Dataviz logo representing a ConnectedMap chart.

A connection map is a map where links between geographical positions are represented using lines or arcs. Most of the time, great circles are used.

This page explains how to build connection maps for the web using d3.js and react. Several tools can be used to display the background map as shown in the dedicated section. The path used to show the connection can then be computed thanks to the geoPath() function of d3.

Useful links

The Data

Two pieces of information are required to build a connection map:

β†’ Geographic information

The first thing you need is the 2d coordinates of the boundaries of the regions you want to represent. If you are trying to build a world map, you need to know where the country boundaries are located πŸ€·β€β™€οΈ.

Several formats exist to store such a piece of information. When working with d3.js, the expected format is geoJSON. A geoJSON file looks pretty much like this:


{
+How to build a connection map component with React and D3.

Connection Map

Dataviz logo representing a ConnectedMap chart.

A connection map is a map where links between geographical positions are represented using lines or arcs. Most of the time, great circles are used.

This page explains how to build connection maps for the web using d3.js and react. Several tools can be used to display the background map as shown in the dedicated section. The path used to show the connection can then be computed thanks to the geoPath() function of d3.

Useful links

The Data

Two pieces of information are required to build a connection map:

β†’ Geographic information

The first thing you need is the 2d coordinates of the boundaries of the regions you want to represent. If you are trying to build a world map, you need to know where the country boundaries are located πŸ€·β€β™€οΈ.

Several formats exist to store such a piece of information. When working with d3.js, the expected format is geoJSON. A geoJSON file looks pretty much like this:


{
   "type": "FeatureCollection",
   "features": [
     {
@@ -97,4 +97,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Connection inspiration

If you're looking for inspiration to create your next Connection, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Connection looks good!

visit
ToDodraw with Canvas
ToDoapplication to a real dataset
ToDohover effect: hover over a city to highlight its connections

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Connection inspiration

If you're looking for inspiration to create your next Connection, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Connection looks good!

visit
ToDodraw with Canvas
ToDoapplication to a real dataset
ToDohover effect: hover over a city to highlight its connections

Map

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/correlogram.html b/correlogram.html index 5ab812d8..028cb207 100644 --- a/correlogram.html +++ b/correlogram.html @@ -1,4 +1,4 @@ -Correlogram with React

Correlogram

Dataviz logo representing a Correlogram chart.

In this blog post, we will be exploring how to build a correlogram with React and D3.js. A correlogram is a graphical representation of the correlation matrix for a given dataset. It is a useful tool for visualizing the relationships between different variables in a dataset, and can help identify potential correlations that may not be immediately obvious.

Building a correlogram with React and D3.js allows us to create a highly interactive and customizable visualization. We will be able to use React's powerful component-based approach to build our visualization, while leveraging the flexibility and power of D3.js to create a dynamic and engaging visual representation of our data.

Useful links

Correlogram = scatter plot + histogram

A correlogram uses histograms to show the distribution of each numeric variable on the diagonal of the matrix. It uses scatter plots to show the relationship of each pair of variable on every other cells.

As a result, it is required to understand how to build a histogram and a scatter plot component using React and d3.js! In this post, we will just show how to leverage those reusable components to build a correlogram.

Picture of a simple histogram made with react and d3.js

Histogram

Learn how to build a histogram with react and d3.js

Picture of a simple scatter plot made with react and d3.js

Scatter plot

Learn how to build a scatter plot with react and d3.js

Picture of a simple bubble plot with a legend made with react and d3.js

Bubble plot

Learn how to build a bubble plot with react and d3.js

The Data

The dataset provides several numeric values for a set of data points. It can also add some categorical variables that can be added to customize the marker colors.

The suggested data structure is an array of object, where each object is a data point. It can have as many numeric properties as needed.


Here is a minimal example of the data structure:

const data = [
+Correlogram with React

Correlogram

Dataviz logo representing a Correlogram chart.

In this blog post, we will be exploring how to build a correlogram with React and D3.js. A correlogram is a graphical representation of the correlation matrix for a given dataset. It is a useful tool for visualizing the relationships between different variables in a dataset, and can help identify potential correlations that may not be immediately obvious.

Building a correlogram with React and D3.js allows us to create a highly interactive and customizable visualization. We will be able to use React's powerful component-based approach to build our visualization, while leveraging the flexibility and power of D3.js to create a dynamic and engaging visual representation of our data.

Useful links

Correlogram = scatter plot + histogram

A correlogram uses histograms to show the distribution of each numeric variable on the diagonal of the matrix. It uses scatter plots to show the relationship of each pair of variable on every other cells.

As a result, it is required to understand how to build a histogram and a scatter plot component using React and d3.js! In this post, we will just show how to leverage those reusable components to build a correlogram.

Picture of a simple histogram made with react and d3.js

Histogram

Learn how to build a histogram with react and d3.js

Picture of a simple scatter plot made with react and d3.js

Scatter plot

Learn how to build a scatter plot with react and d3.js

Picture of a simple bubble plot with a legend made with react and d3.js

Bubble plot

Learn how to build a bubble plot with react and d3.js

The Data

The dataset provides several numeric values for a set of data points. It can also add some categorical variables that can be added to customize the marker colors.

The suggested data structure is an array of object, where each object is a data point. It can have as many numeric properties as needed.


Here is a minimal example of the data structure:

const data = [
   {var1: 5.1, var2: 3.5, ..., group: 'setosa'},
   {var1: 4.9, var2: 3.0, ..., group: 'setosa'},
   ...
@@ -49,4 +49,4 @@
       {allGraphs}
     </div>
   </div>
-);

And voilà, a first decent correlogram for your data analysis pipeline 😊. It's not perfect yet. You probably want to give more love to axes and labels, add hover effect and tooltips. But hopefully that's a good template to get started.

44.555.566.577.58
44.555.566.577.58
44.555.566.577.58
22.533.54var2
22.533.54
22.533.54
1234567var3
1234567
1234567
00.511.522.5var4var1
00.511.522.5var2
00.511.522.5var3

A correlogram built with react and d3.js. It shows the relationship between the 4 numeric variables of the famous iris dataset.

Note: You can compare this code with the pure d3 alternative. I find it much more readable.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +);

And voilà, a first decent correlogram for your data analysis pipeline 😊. It's not perfect yet. You probably want to give more love to axes and labels, add hover effect and tooltips. But hopefully that's a good template to get started.

44.555.566.577.58
44.555.566.577.58
44.555.566.577.58
22.533.54var2
22.533.54
22.533.54
1234567var3
1234567
1234567
00.511.522.5var4var1
00.511.522.5var2
00.511.522.5var3

A correlogram built with react and d3.js. It shows the relationship between the 4 numeric variables of the famous iris dataset.

Note: You can compare this code with the pure d3 alternative. I find it much more readable.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/cross-graph-highlight-interaction.html b/cross-graph-highlight-interaction.html index e6359a24..1113f8f8 100644 --- a/cross-graph-highlight-interaction.html +++ b/cross-graph-highlight-interaction.html @@ -1,8 +1,8 @@ -Cross graph highlight interaction

Cross graph highlight interaction


This post explains how to add cross graph interactions in a react app. It focus on performance, showing how a naive approach with a shared state leads to a disappointing result and how a react context can solve the problem.

Disclaimer: the concepts explained here where showed to me by my colleague Gabriel Vergnaud.

-What is cross graph interaction

What it is.

working example

Why do we care?

Focus on performance

+Naive solution: a shared state

A first solution: a shared state. You defined a react state at the level of the component that wraps all your viz with useState:

const [group, setGroup] = useState<number | null>(null);

You then pass the state and the setter function to each viz. Something like:

<Barplot
+Cross graph highlight interaction

Cross graph highlight interaction


This post explains how to add cross graph interactions in a react app. It focus on performance, showing how a naive approach with a shared state leads to a disappointing result and how a react context can solve the problem.

Disclaimer: the concepts explained here where showed to me by my colleague Gabriel Vergnaud.

-What is cross graph interaction

What it is.

working example

Why do we care?

Focus on performance

+Naive solution: a shared state

A first solution: a shared state. You defined a react state at the level of the component that wraps all your viz with useState:

const [group, setGroup] = useState<number | null>(null);

You then pass the state and the setter function to each viz. Something like:

<Barplot
   width={300}
   height={220}
   group={group}
   setGroup={setGroup}
 />

Then, for each shape item of the graph you're building, you check wether or not the shape should be highlighted, and changes the way it's rendered if so.

In the example below I slightly increase the opacity, so the div as this in its style attribute:

style={{
   opacity: group === i ? 1 : 0.4,
-}}

Here is the result for 4 barplots with 1500 items each:

Four barplots with 1500 groups each. Hovering a group on a chart highlights it on other charts, with very poor performances.

As you can see it works, but is very slow.

+Improving rerendering

A first solution: a shared state.

Four barplots with 3000 groups each. Hovering a group on a chart highlights it on other charts, with very poor performances.

Why is it so slow?

-React context and event emitter to the rescue

Use a context to improve perf

React documentation about context

Context is primarily used when some data needs to be accessible by many components at different nesting levels.

Step 1 is to create the context with createContext.

Doc about CustomEvent(): linkBasically you do const catFound = new CustomEvent('animalfound'). catFound is a CustomEvent. You can trigger it with

Four barplots with 3000 groups each. Hovering a group on a chart highlights it on other charts, with very poor performances.

-Conclusion

Article explains how to create a performant cross graph interaction using a react context and an event emitter.

But there is more even more you should do

  • use debounce and throttling to avoid too many concurrent re-renders
  • don't highlight graphs that are outside of the view port



Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}}

Here is the result for 4 barplots with 1500 items each:

Four barplots with 1500 groups each. Hovering a group on a chart highlights it on other charts, with very poor performances.

As you can see it works, but is very slow.

+Improving rerendering

A first solution: a shared state.

Four barplots with 3000 groups each. Hovering a group on a chart highlights it on other charts, with very poor performances.

Why is it so slow?

-React context and event emitter to the rescue

Use a context to improve perf

React documentation about context

Context is primarily used when some data needs to be accessible by many components at different nesting levels.

Step 1 is to create the context with createContext.

Doc about CustomEvent(): linkBasically you do const catFound = new CustomEvent('animalfound'). catFound is a CustomEvent. You can trigger it with

Four barplots with 3000 groups each. Hovering a group on a chart highlights it on other charts, with very poor performances.

-Conclusion

Article explains how to create a performant cross graph interaction using a react context and an event emitter.

But there is more even more you should do

  • use debounce and throttling to avoid too many concurrent re-renders
  • don't highlight graphs that are outside of the view port



Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/dataset-transition.html b/dataset-transition.html index f6c9b283..b434a8e4 100644 --- a/dataset-transition.html +++ b/dataset-transition.html @@ -1,4 +1,4 @@ -Smooth dataset transition

Animated dataset transition


How to smoothly transition from a dataset to the other. Use the react-spring library. Several examples with explanation. Start simple. Then focus on tricky things like enter, exit, axis, path.

A minimal react-spring dataviz example. A viz component expect a position and a color prop. But it smoothly animates the transition.

-Most basic: barplot transition

Consider a change where dataset has the same structure, just the values change. Same number of items.

Also, just animating a prop of a shape

Very simple, just animate the bar width

Spring looks like this

const springProps = useSpring({
+Smooth dataset transition

Animated dataset transition


How to smoothly transition from a dataset to the other. Use the react-spring library. Several examples with explanation. Start simple. Then focus on tricky things like enter, exit, axis, path.

A minimal react-spring dataviz example. A viz component expect a position and a color prop. But it smoothly animates the transition.

-Most basic: barplot transition

Consider a change where dataset has the same structure, just the values change. Same number of items.

Also, just animating a prop of a shape

Very simple, just animate the bar width

Spring looks like this

const springProps = useSpring({
   to: {
     barWidth,
   }
@@ -8,4 +8,4 @@
   width={springProps.barWidth}
   height={height}
   fill="#9d174d"
-/>

Most basic dataviz animation with react spring. The width of each bar is smoothly updated with an animation.

-Custom Enter: scatterplot transition

Axis limits set to 0 to 100. No need to animate axis for now.

Most of the circles just have their x and Y positions that update, no big deal.

Blue and red point exist only in dataset 1 and 2 respectively. We need to make them enter and leave the scene properly.

A very basic animation using react and react-spring.

-Animating a path: donut transition

Donut is more tricky since each shape is a path. As a result, we need to compute the d property for each frame of the animation.

This is possible thanks to the to() function

A very basic animation using react and react-spring.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +/>

Most basic dataviz animation with react spring. The width of each bar is smoothly updated with an animation.

-Custom Enter: scatterplot transition

Axis limits set to 0 to 100. No need to animate axis for now.

Most of the circles just have their x and Y positions that update, no big deal.

Blue and red point exist only in dataset 1 and 2 respectively. We need to make them enter and leave the scene properly.

A very basic animation using react and react-spring.

-Animating a path: donut transition

Donut is more tricky since each shape is a path. As a result, we need to compute the d property for each frame of the animation.

This is possible thanks to the to() function

A very basic animation using react and react-spring.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/dendrogram.html b/dendrogram.html index 3ed722dd..11ea09e3 100644 --- a/dendrogram.html +++ b/dendrogram.html @@ -1,4 +1,4 @@ -Dendrogram | The React Graph Gallery

Dendrogram

Dataviz logo representing a Dendrogram chart.

A dendrogram is a network structure. It is constituted of a root node that gives birth to several nodes connected by edges or branches. The last nodes of the hierarchy are called leaves.

This page explains how to build a dendrogram using d3.js to compute the node position, and React to render the nodes and edges. It starts by describing the required data format, explains how to build a very basicdendrogram and then shows how to customize it.

Useful links

The Data

The dataset describes a hierarchy using a recursive structure.

Each item in this structure is called a node. The lowest nodes of the hierarchy being called leaves. The dataset is an object that has at least 3 properties: name, value and children. Children is an array of nodes that have this structure too.

Here is a minimal example of the data structure:

const data = {
+Dendrogram | The React Graph Gallery

Dendrogram

Dataviz logo representing a Dendrogram chart.

A dendrogram is a network structure. It is constituted of a root node that gives birth to several nodes connected by edges or branches. The last nodes of the hierarchy are called leaves.

This page explains how to build a dendrogram using d3.js to compute the node position, and React to render the nodes and edges. It starts by describing the required data format, explains how to build a very basicdendrogram and then shows how to customize it.

Useful links

The Data

The dataset describes a hierarchy using a recursive structure.

Each item in this structure is called a node. The lowest nodes of the hierarchy being called leaves. The dataset is an object that has at least 3 properties: name, value and children. Children is an array of nodes that have this structure too.

Here is a minimal example of the data structure:

const data = {
   type: 'node',
   name: "boss",
   value: 2300,
@@ -49,4 +49,4 @@
 />
MarkRobertEmilyMarionNicolasMalkiDjΓ©MΓ©lanieEinstein

Horizontal dendrogram with smooth edges made with react and d3.js.

Radial dendrogram

The radial dendrogram is a bit trickier to achieve.

β†’ polar coordinates

We are dealing with polar coordinates here. As a result, the size attribute of thelayout()function must be updated.

  • The first item is 360. It will define the angle (in degree) to follow to reach a node. 0 is on top.
  • The second item is the radius of the figure. It will provide the distance to the center of a node in pixel.
const dendrogramGenerator = d3
   .cluster()
   .size([360, radius]);
-const dendrogram = dendrogramGenerator(hierarchy);

Since x and y are now describing an angle and a distance to the center, we can position a node using the following transform property:

transform={"rotate(" + (node.x - 90) + ")translate(" + node.y + ")"}

β†’ Smooth edges with linkRadial

Edges are not horizontal anymore, so the linkHorizontal won't be helpful this time. But instead, the d3.linkRadial function does the job based on an angle and a distance.

β†’ Smart labels

Please make sure your labels are properly oriented. It always give a bit of a headhache to pivot them correctly, and to control the anchoring appropriately. I talked about it extensively in the circular barplot section so please take a look for this matter.

;;;MarkRobertEmilyMarionNicolasMalkiDjΓ©MΓ©lanieEinstein

A minimalist radial dendrogram built using d3 and react.

Note: please check of the first level edges are straight lines. IMO it does not make sense to use linkRadial for the first level.

Coming next

There is much more that needs to be added to this tutorial.

Using canvas for rendering is often a requirement when the number of nodes gets big. Interactivity is often necessary, for hover effect or to collapse a part of the tree. It also possible to map the node circle size to a numeric variable.

This will come soon! I have a newsletter called the dataviz universe where I share my latest updates.

Subscribe

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +const dendrogram = dendrogramGenerator(hierarchy);

Since x and y are now describing an angle and a distance to the center, we can position a node using the following transform property:

transform={"rotate(" + (node.x - 90) + ")translate(" + node.y + ")"}

β†’ Smooth edges with linkRadial

Edges are not horizontal anymore, so the linkHorizontal won't be helpful this time. But instead, the d3.linkRadial function does the job based on an angle and a distance.

β†’ Smart labels

Please make sure your labels are properly oriented. It always give a bit of a headhache to pivot them correctly, and to control the anchoring appropriately. I talked about it extensively in the circular barplot section so please take a look for this matter.

;;;MarkRobertEmilyMarionNicolasMalkiDjΓ©MΓ©lanieEinstein

A minimalist radial dendrogram built using d3 and react.

Note: please check of the first level edges are straight lines. IMO it does not make sense to use linkRadial for the first level.

Coming next

There is much more that needs to be added to this tutorial.

Using canvas for rendering is often a requirement when the number of nodes gets big. Interactivity is often necessary, for hover effect or to collapse a part of the tree. It also possible to map the node circle size to a numeric variable.

This will come soon! I have a newsletter called the dataviz universe where I share my latest updates.

Subscribe

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/density-plot.html b/density-plot.html index 45ebd95b..731896e3 100644 --- a/density-plot.html +++ b/density-plot.html @@ -1,4 +1,4 @@ -Density chart with React

Density chart

Dataviz logo representing a Density chart.

A density plot is a chart type that shows the distribution of a numeric variable. This page is a step-by-step guide on how to build your own density plot for the web, using React and D3.js.

It starts by describing how the data should be organized and how to initialize the density component. It then explains how to compute a kernel density. Once this is done, it shows how to render the density shape and suggests a few variations. πŸ™‡β€β™‚οΈ.

Useful links

The Data

Building a density chart only requires a set of numeric values.

As a result, the dataset is pretty simple: just an array of number.


Here is a minimal example of the data structure:

export const data = [
+Density chart with React

Density chart

Dataviz logo representing a Density chart.

A density plot is a chart type that shows the distribution of a numeric variable. This page is a step-by-step guide on how to build your own density plot for the web, using React and D3.js.

It starts by describing how the data should be organized and how to initialize the density component. It then explains how to compute a kernel density. Once this is done, it shows how to render the density shape and suggests a few variations. πŸ™‡β€β™‚οΈ.

Useful links

The Data

Building a density chart only requires a set of numeric values.

As a result, the dataset is pretty simple: just an array of number.


Here is a minimal example of the data structure:

export const data = [
   75.0,
   104.0,
   369.0,
@@ -83,4 +83,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Density inspiration

If you're looking for inspiration to create your next Density, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Density looks good!

visit

Variations

Once you've understood how to build a basic density chart with d3 and React, it opens an infinite world of customization.

Here is an example showing how to plot several distributions on the same figure, allowing to compare several groups.

Using small multiple to visualize the distribution of several groups in 1 figure, avoiding overlapping.

Note that an alternative could be to use small multiple. See this histogram example that you should be able to adapt quickly.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Density inspiration

If you're looking for inspiration to create your next Density, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Density looks good!

visit

Variations

Once you've understood how to build a basic density chart with d3 and React, it opens an infinite world of customization.

Here is an example showing how to plot several distributions on the same figure, allowing to compare several groups.

Using small multiple to visualize the distribution of several groups in 1 figure, avoiding overlapping.

Note that an alternative could be to use small multiple. See this histogram example that you should be able to adapt quickly.

Distribution

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/donut.html b/donut.html index 25611b03..c8a3cd96 100644 --- a/donut.html +++ b/donut.html @@ -1,4 +1,4 @@ -Donut chart | The React Graph Gallery

Donut chart

Dataviz logo representing a Doughnut chart.

The donut chart is a very common yet criticized way to represent the value of a few groups in a dataset. It is very close to the pie chart and thus suffers the same downsides.

This page explains how to build a donut chart using d3.js and React. It starts with a basic example and then focus on customization like legends, hover effect and dataset transition.

Useful links

The Data

The dataset required to build a donut chart is an array where each item represents a group. Each item is an object with 2 properties. They provide the group name (name) and its value (value).


For instance, here is the dataset used for the simple donut chart below:

const data = [
+Donut chart | The React Graph Gallery

Donut chart

Dataviz logo representing a Doughnut chart.

The donut chart is a very common yet criticized way to represent the value of a few groups in a dataset. It is very close to the pie chart and thus suffers the same downsides.

This page explains how to build a donut chart using d3.js and React. It starts with a basic example and then focus on customization like legends, hover effect and dataset transition.

Useful links

The Data

The dataset required to build a donut chart is an array where each item represents a group. Each item is an object with 2 properties. They provide the group name (name) and its value (value).


For instance, here is the dataset used for the simple donut chart below:

const data = [
   {name:"Mark", value: 90},
   {name:"Robert", value: 12},
   {name:"Emily", value: 34},
@@ -45,4 +45,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Donut inspiration

If you're looking for inspiration to create your next Donut, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Donut looks good!

visit

Hover effect

On the graph below, hovering over a slice will smoothly highlight it, giving a nice polish touch to the widget.

The process is quickly described on the pie chart hover effect section. But hover effect is a topic on itself. As a result, I plan to write a full tutorial targeting this topic only. You can subscribe to know when it's ready!

Tell me when the Hover effect post is ready!

Meanwhile, here is a donut chart with a hover effect, together with its React code:

Mark (90)Robert (12)Emily (34)Marion (53)Nicolas (58)

A donut chart with clean inline legends, built thanks to the centroid function of d3.js.

Data transition

The Pie component expects a data prop. What should we do when this data changes?

By default, the chart will update instantly, with no transition. Adding a smooth transition gives a nice polish touch to the graph. Try to switch between the 2 datasets below to see the animation in action.

The code below relies on the react-spring library. Instead of rendering a path for each slice, it uses a animated.path component that handles the spring animation for us.

The implementation is not trivial. I plan to publish a full tutorial on react-spring for data visualization soon. You can subscribe here to be notified when it is ready.

A donut chart with clean inline legends, built thanks to the centroid function of d3.js.

Note: check the blue group that appears / disappears between dataset. This kind of enter/exit pattern is something to keep in mind when building animations.

Pie chart to barplot

Pie charts are often criticized since angles are hard to read. Let's represent the same data using a pie chart or a barplot, to see what's the most insightful πŸ€·β€β™‚οΈ.

Note that here we animate the transition between different shape types: each arc becomes a rectangle and reciprocally. This is made possible thanks to the flubber library, used in coordination with react-spring.

Once more, a full tutorial is needed here. You can subscribe here to be notified when it is ready. In the meanwhile, the code of this specific example is provided below.

Transition from a pie chart to a barplot with a smooth animation using the buttons on top.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Donut inspiration

If you're looking for inspiration to create your next Donut, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Donut looks good!

visit

Hover effect

On the graph below, hovering over a slice will smoothly highlight it, giving a nice polish touch to the widget.

The process is quickly described on the pie chart hover effect section. But hover effect is a topic on itself. As a result, I plan to write a full tutorial targeting this topic only. You can subscribe to know when it's ready!

Tell me when the Hover effect post is ready!

Meanwhile, here is a donut chart with a hover effect, together with its React code:

Mark (90)Robert (12)Emily (34)Marion (53)Nicolas (58)

A donut chart with clean inline legends, built thanks to the centroid function of d3.js.

Data transition

The Pie component expects a data prop. What should we do when this data changes?

By default, the chart will update instantly, with no transition. Adding a smooth transition gives a nice polish touch to the graph. Try to switch between the 2 datasets below to see the animation in action.

The code below relies on the react-spring library. Instead of rendering a path for each slice, it uses a animated.path component that handles the spring animation for us.

The implementation is not trivial. I plan to publish a full tutorial on react-spring for data visualization soon. You can subscribe here to be notified when it is ready.

A donut chart with clean inline legends, built thanks to the centroid function of d3.js.

Note: check the blue group that appears / disappears between dataset. This kind of enter/exit pattern is something to keep in mind when building animations.

Pie chart to barplot

Pie charts are often criticized since angles are hard to read. Let's represent the same data using a pie chart or a barplot, to see what's the most insightful πŸ€·β€β™‚οΈ.

Note that here we animate the transition between different shape types: each arc becomes a rectangle and reciprocally. This is made possible thanks to the flubber library, used in coordination with react-spring.

Once more, a full tutorial is needed here. You can subscribe here to be notified when it is ready. In the meanwhile, the code of this specific example is provided below.

Transition from a pie chart to a barplot with a smooth animation using the buttons on top.

Part Of A Whole

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/arc-diagram-vertical.html b/example/arc-diagram-vertical.html index 98e3e3d1..e19ef2f5 100644 --- a/example/arc-diagram-vertical.html +++ b/example/arc-diagram-vertical.html @@ -1,4 +1,4 @@ -How to build a vertical arc diagram with React and D3.js.

Vertical arc diagram

Dataviz logo representing a Arc chart.

This tutorial is a variation around the general introduction to arc diagram with react and d3.js. You should probably understand the concepts described there before reading here.

This example explains how to make a vertical version of the arc diagram. The vertical version is sometimes prefered as it makes it easier to read the node labels.

A code sandbox is provided for the final result, but explanations target what's different compared to a classic horizontal arc diagram.

Useful links

Plot and code

If you are in a hurry, here is the final plot we're trying to achieve here, together with its code:πŸ™‡β€β™‚οΈ

It is a very simple vertical arc diagram, a variation of thehorizontal version deeply described in the arc diagram section of the gallery

Arc section

A vertical arc diagram made with d3.js and react.

Vertical arcs

The main difficulty when it comes to make an arc diagram is to draw arcs in SVG.

The function allowing to draw arcs between 2 data points is a bit complicated since it requires to use elliptical arc curves.

You can read more explanation about the syntax in the official doc. But in the meantime here is the function I suggest to draw an arc connecting 2 points vertically:

const verticalArcGenerator = (
+How to build a vertical arc diagram with React and D3.js.

Vertical arc diagram

Dataviz logo representing a Arc chart.

This tutorial is a variation around the general introduction to arc diagram with react and d3.js. You should probably understand the concepts described there before reading here.

This example explains how to make a vertical version of the arc diagram. The vertical version is sometimes prefered as it makes it easier to read the node labels.

A code sandbox is provided for the final result, but explanations target what's different compared to a classic horizontal arc diagram.

Useful links

Plot and code

If you are in a hurry, here is the final plot we're trying to achieve here, together with its code:πŸ™‡β€β™‚οΈ

It is a very simple vertical arc diagram, a variation of thehorizontal version deeply described in the arc diagram section of the gallery

Arc section

A vertical arc diagram made with d3.js and react.

Vertical arcs

The main difficulty when it comes to make an arc diagram is to draw arcs in SVG.

The function allowing to draw arcs between 2 data points is a bit complicated since it requires to use elliptical arc curves.

You can read more explanation about the syntax in the official doc. But in the meantime here is the function I suggest to draw an arc connecting 2 points vertically:

const verticalArcGenerator = (
   xStart: number,
   yStart: number,
   xEnd: number,
@@ -22,4 +22,4 @@
     ",",
     yEnd,
   ].join(" ");
-};

Labels

Note that some labels have been added here compared to the vertical version.

This is the main advantage of choosing the horizontal layout!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +};

Labels

Note that some labels have been added here compared to the vertical version.

This is the main advantage of choosing the horizontal layout!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/barplot-data-transition-animation.html b/example/barplot-data-transition-animation.html index 66ca31d3..ba9108b3 100644 --- a/example/barplot-data-transition-animation.html +++ b/example/barplot-data-transition-animation.html @@ -1,4 +1,4 @@ -Barplot with smooth dataset transition.

Barplot

Dataviz logo representing a Bar chart.

This tutorial is a variation around the general introduction to barplot with react and d3.js. You should probably understand the concepts described there before digging into animation.

This example focus on how to transition between datasets. It explains how to animate the change thanks to the react-spring library.

A code sandbox is provided for the final result, but explanations target what's different compared to an usual barplot.

Useful links

Plot and code

If you are in a hurry, this is what we're trying to achieve here πŸ™‡β€β™‚οΈ. The value of several individuals is represented, with one bar per individual. It's just a horizontal barplot.

It is possible to switch from one dataset to another using the buttons above the chart. A few notes on the 3 usual animation patterns:

  • update: bars smoothly update their rank and size when the data changes. So does their label.
  • enter: when the chart first loads, bar starts from 0 and grows to its real size. This is also true for items that are available in the new dataset but not in the previous. Check Christophe when you switch to data 2.
  • exit: when an item is not available in the next dataset, it disappears with no animation (see Paul when switching to data2).

Barplot with smooth transition between dataset

The Data

The dataset used here is exactly the same as the one used for the simple barplot. Note that 2 similar datasets are used: data1 and data2.

Animation

Most of the code is similar to the basic barplot component. But instead of building one rect per item in the dataset, a BarItem component is called to render a rectangle that supports animation.

The react-spring library is used to create a spring animation. The rectangle properties are passed to a useSpring hook that will build the animation for us.

This is how the BarItem component looks like:

import { useSpring, animated } from "@react-spring/web";
+Barplot with smooth dataset transition.

Barplot

Dataviz logo representing a Bar chart.

This tutorial is a variation around the general introduction to barplot with react and d3.js. You should probably understand the concepts described there before digging into animation.

This example focus on how to transition between datasets. It explains how to animate the change thanks to the react-spring library.

A code sandbox is provided for the final result, but explanations target what's different compared to an usual barplot.

Useful links

Plot and code

If you are in a hurry, this is what we're trying to achieve here πŸ™‡β€β™‚οΈ. The value of several individuals is represented, with one bar per individual. It's just a horizontal barplot.

It is possible to switch from one dataset to another using the buttons above the chart. A few notes on the 3 usual animation patterns:

  • update: bars smoothly update their rank and size when the data changes. So does their label.
  • enter: when the chart first loads, bar starts from 0 and grows to its real size. This is also true for items that are available in the new dataset but not in the previous. Check Christophe when you switch to data 2.
  • exit: when an item is not available in the next dataset, it disappears with no animation (see Paul when switching to data2).

Barplot with smooth transition between dataset

The Data

The dataset used here is exactly the same as the one used for the simple barplot. Note that 2 similar datasets are used: data1 and data2.

Animation

Most of the code is similar to the basic barplot component. But instead of building one rect per item in the dataset, a BarItem component is called to render a rectangle that supports animation.

The react-spring library is used to create a spring animation. The rectangle properties are passed to a useSpring hook that will build the animation for us.

This is how the BarItem component looks like:

import { useSpring, animated } from "@react-spring/web";
 
 type BarItemProps = {
   name: string;
@@ -73,4 +73,4 @@
       </animated.text>
     </g>
   );
-};

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +};

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/barplot-stacked-horizontal.html b/example/barplot-stacked-horizontal.html index 359ee853..59ce1e56 100644 --- a/example/barplot-stacked-horizontal.html +++ b/example/barplot-stacked-horizontal.html @@ -1,4 +1,4 @@ -Horizontal stacked barplot.

Horizontal Stacked Barplot

Dataviz logo representing a Bar chart.

This tutorial is a variation around the general introduction to barplot with react and d3.js. You should probably understand the concepts described there before digging into stacking.

This example shows how to represent 2 levels of grouping in a barplot, resulting in a stacked barplot. The items of the dataset are divided in groups (reprented as bars) and subgroups (represented as sections in each bar).

A code sandbox is provided for the final result, but explanations target what's different compared to an usual barplot.

Useful links

Plot and code

This is a stacked barplot built using React and d3.js. The dummy dataset provides information about how much my friends spent the last month. The people are the group here. Each bar represents a group.

A second level of grouping is available. We know if the money was spent on travel, food or beer. It is possible to represent this additional amount of info using a process called stacking.

How much my friends spend on travel, food and beer.
50100150200250300312Jean294Nicolas270Mark159Marion102Emily69MΓ©lanie54Gabriel36Robert6Paul

A horizontal stacked barplot built with d3.js for scales, and react for rendering

Now, let's see how to implement such a graph.

The Data

There are several ways to store this information in javascript. I suggest an array of object where each object provides the valueof 1 specific expense, with the group (friend name) and the subgroup (category of expense).

export const data = [
+Horizontal stacked barplot.

Horizontal Stacked Barplot

Dataviz logo representing a Bar chart.

This tutorial is a variation around the general introduction to barplot with react and d3.js. You should probably understand the concepts described there before digging into stacking.

This example shows how to represent 2 levels of grouping in a barplot, resulting in a stacked barplot. The items of the dataset are divided in groups (reprented as bars) and subgroups (represented as sections in each bar).

A code sandbox is provided for the final result, but explanations target what's different compared to an usual barplot.

Useful links

Plot and code

This is a stacked barplot built using React and d3.js. The dummy dataset provides information about how much my friends spent the last month. The people are the group here. Each bar represents a group.

A second level of grouping is available. We know if the money was spent on travel, food or beer. It is possible to represent this additional amount of info using a process called stacking.

How much my friends spend on travel, food and beer.
50100150200250300312Jean294Nicolas270Mark159Marion102Emily69MΓ©lanie54Gabriel36Robert6Paul

A horizontal stacked barplot built with d3.js for scales, and react for rendering

Now, let's see how to implement such a graph.

The Data

There are several ways to store this information in javascript. I suggest an array of object where each object provides the valueof 1 specific expense, with the group (friend name) and the subgroup (category of expense).

export const data = [
   {group:"Mark", subgroup: "travel",  value: 90},
   {group:"Mark", subgroup: "food",  value: 23},
   {group:"Mark", subgroup: "beer",  value: 14},
@@ -26,4 +26,4 @@
     [34, 68, data: 'Emily'],
     ...
   ]
-]

Rendering

Once you get the stacked data above, rendering the chart is business as usual. You can loop through the object and plot a rect for each item.

How much my friends spend on travel, food and beer.
50100150200250300312Jean294Nicolas270Mark159Marion102Emily69MΓ©lanie54Gabriel36Robert6Paul

A horizontal stacked barplot built with d3.js for scales, and react for rendering

Variation

Check those other barplot and stacked barplot that can interest you:

Picture of a horizontal barplot made with React and d3

Basic barplot

Most basic barplot built with React and d3

GIF of a data update on a React barplot

Barplot dataset transition

How to smoothly animate the transition between dataset

Picture of a vertical stacked barchart made with react and d3

Vertical Stacked Barplot

Represent group and subgroup values by stacking the data

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +]

Rendering

Once you get the stacked data above, rendering the chart is business as usual. You can loop through the object and plot a rect for each item.

How much my friends spend on travel, food and beer.
50100150200250300312Jean294Nicolas270Mark159Marion102Emily69MΓ©lanie54Gabriel36Robert6Paul

A horizontal stacked barplot built with d3.js for scales, and react for rendering

Variation

Check those other barplot and stacked barplot that can interest you:

Picture of a horizontal barplot made with React and d3

Basic barplot

Most basic barplot built with React and d3

GIF of a data update on a React barplot

Barplot dataset transition

How to smoothly animate the transition between dataset

Picture of a vertical stacked barchart made with react and d3

Vertical Stacked Barplot

Represent group and subgroup values by stacking the data

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/barplot-stacked-vertical.html b/example/barplot-stacked-vertical.html index 6a201bd1..046c115e 100644 --- a/example/barplot-stacked-vertical.html +++ b/example/barplot-stacked-vertical.html @@ -1 +1 @@ -Vertical stacked barplot.

Vertical Stacked Barplot

Dataviz logo representing a Bar chart.

This tutorial is a variation around the general introduction to barplot with react and d3.js. You should probably understand the concepts described there before digging into stacking.

This example shows how to represent 2 levels of grouping in a barplot, resulting in a stacked barplot. The items of the dataset are divided in groups (reprented as bars) and subgroups (represented as sections in each bar).

A code sandbox is provided for the final result, but explanations target what's different compared to an usual barplot.

Useful links

Plot and code

This is a vertical stacked barplot built using React and d3.js. It is very similar to the horizontal version. So very little explanation is provided here. Enjoy the sandbox!

Most basic barplot built with d3.js for scales, and react for rendering

Variation

Check those other barplot and stacked barplot that can interest you:

Picture of a horizontal barplot made with React and d3

Basic barplot

Most basic barplot built with React and d3

GIF of a data update on a React barplot

Barplot dataset transition

How to smoothly animate the transition between dataset

Picture of a stacked barchart made with react and d3

Horizontal Stacked Barplot

Represent group and subgroup values by stacking the data

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +Vertical stacked barplot.

Vertical Stacked Barplot

Dataviz logo representing a Bar chart.

This tutorial is a variation around the general introduction to barplot with react and d3.js. You should probably understand the concepts described there before digging into stacking.

This example shows how to represent 2 levels of grouping in a barplot, resulting in a stacked barplot. The items of the dataset are divided in groups (reprented as bars) and subgroups (represented as sections in each bar).

A code sandbox is provided for the final result, but explanations target what's different compared to an usual barplot.

Useful links

Plot and code

This is a vertical stacked barplot built using React and d3.js. It is very similar to the horizontal version. So very little explanation is provided here. Enjoy the sandbox!

Most basic barplot built with d3.js for scales, and react for rendering

Variation

Check those other barplot and stacked barplot that can interest you:

Picture of a horizontal barplot made with React and d3

Basic barplot

Most basic barplot built with React and d3

GIF of a data update on a React barplot

Barplot dataset transition

How to smoothly animate the transition between dataset

Picture of a stacked barchart made with react and d3

Horizontal Stacked Barplot

Represent group and subgroup values by stacking the data

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/boxplot-horizontal.html b/example/boxplot-horizontal.html index acb9419e..71fd0885 100644 --- a/example/boxplot-horizontal.html +++ b/example/boxplot-horizontal.html @@ -1,4 +1,4 @@ -Horizontal Boxplot

Horizontal Boxplot

Dataviz logo representing a Box1 chart.

This tutorial is a variation around the general introduction to boxplot with react and d3.js. You should probably understand the concepts described there before reading here.

The general introduction relies on a VerticalBox function that draws a.. vertical box πŸ™ƒ. The main difference here is that we are now building a HorizontalBox function and swap the X and Y axes.

As usual, this post comes with explanation, a code sandbox and a template that you can reuse instantly in your web application.

Useful links

Horizontal Boxplot implementation

Here is a proposal of implementation for a horizontal boxplot with react and d3.js.

D3 actually has a very minor role here. It is only used to compute the xand y scales. The x scale is a linear scale made with the scaleLinear() function. The Y scale shows groups thanks to the scaleBand() function.

ABCD

A horizontal boxplot made with React and D3.js.

Horizontal box drawing

We need a function that draws a horizontal box in SVG based on the quartiles position in pixels.

The function looks like this:

export const HorizontalBox = ({
+Horizontal Boxplot

Horizontal Boxplot

Dataviz logo representing a Box1 chart.

This tutorial is a variation around the general introduction to boxplot with react and d3.js. You should probably understand the concepts described there before reading here.

The general introduction relies on a VerticalBox function that draws a.. vertical box πŸ™ƒ. The main difference here is that we are now building a HorizontalBox function and swap the X and Y axes.

As usual, this post comes with explanation, a code sandbox and a template that you can reuse instantly in your web application.

Useful links

Horizontal Boxplot implementation

Here is a proposal of implementation for a horizontal boxplot with react and d3.js.

D3 actually has a very minor role here. It is only used to compute the xand y scales. The x scale is a linear scale made with the scaleLinear() function. The Y scale shows groups thanks to the scaleBand() function.

ABCD

A horizontal boxplot made with React and D3.js.

Horizontal box drawing

We need a function that draws a horizontal box in SVG based on the quartiles position in pixels.

The function looks like this:

export const HorizontalBox = ({
   min,
   q1,
   median,
@@ -36,4 +36,4 @@
       />
     </>
   );
-};

Next steps

This post is a translation of the basic boxplot example, switching from vertical to horizontal mode.

Now that this basic horizontal boxplot is available, it should be straightforward to add interesting features like showing individual data points or switching to a violin plot.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +};

Next steps

This post is a translation of the basic boxplot example, switching from vertical to horizontal mode.

Now that this basic horizontal boxplot is available, it should be straightforward to add interesting features like showing individual data points or switching to a violin plot.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/boxplot-jitter.html b/example/boxplot-jitter.html index d752e7d8..dc8f8ca1 100644 --- a/example/boxplot-jitter.html +++ b/example/boxplot-jitter.html @@ -1,4 +1,4 @@ -How to build a boxplot with individual data points displayed on top using jittering.

Boxplot

Dataviz logo representing a Box1 chart.

This tutorial is a variation around the general introduction to boxplot with react and d3.js. You should probably understand the concepts described there before reading here.

This example explains how to display all individual data points of the dataset on top of each box, using jittering to avoid overlaps.

A code sandbox is provided for the final result, but explanations target what's different compared to an usual boxplot.

Useful links

Plot and code

If you are in a hurry, this is what we're trying to achieve here.πŸ™‡β€β™‚οΈ

The distribution of several groups is represented, with one box for each group. This kind of viz is called a boxplot and has its own boxplot section.

Even if powerful to summarize the distribution of a numeric variable, the boxplot has flaws.

It basically hides the underlying distribution. For instance, a low sample size or a bi-modal distribution are impossible to detect reading the boxes only.

Jittering is a good workaround. Add all individual data points with low size, low opacity, and some random shift to the right or to the left (jitter). The underlying distribution becomes instantly available.

-5051015202530ABCD

Showing individual data points using jittering on top of your boxplot adds trust. Reader now knows you're not hiding anything.

The Data

The dataset used here is exactly the same as the one used for the simple boxplot.

Jittering

We want to show each individual data point on top of each box for accuracy. If the dataset is big, this would result in a cluttered figure with a lot of overlap.

Jittering is a process that shifts each circle by a random value. It avoids the overlap, and allows to make the circle layer insightful.

Here is a suggestion to implement it:

const allCircles = groupData.map((value, i) => (
+How to build a boxplot with individual data points displayed on top using jittering.

Boxplot

Dataviz logo representing a Box1 chart.

This tutorial is a variation around the general introduction to boxplot with react and d3.js. You should probably understand the concepts described there before reading here.

This example explains how to display all individual data points of the dataset on top of each box, using jittering to avoid overlaps.

A code sandbox is provided for the final result, but explanations target what's different compared to an usual boxplot.

Useful links

Plot and code

If you are in a hurry, this is what we're trying to achieve here.πŸ™‡β€β™‚οΈ

The distribution of several groups is represented, with one box for each group. This kind of viz is called a boxplot and has its own boxplot section.

Even if powerful to summarize the distribution of a numeric variable, the boxplot has flaws.

It basically hides the underlying distribution. For instance, a low sample size or a bi-modal distribution are impossible to detect reading the boxes only.

Jittering is a good workaround. Add all individual data points with low size, low opacity, and some random shift to the right or to the left (jitter). The underlying distribution becomes instantly available.

-5051015202530ABCD

Showing individual data points using jittering on top of your boxplot adds trust. Reader now knows you're not hiding anything.

The Data

The dataset used here is exactly the same as the one used for the simple boxplot.

Jittering

We want to show each individual data point on top of each box for accuracy. If the dataset is big, this would result in a cluttered figure with a lot of overlap.

Jittering is a process that shifts each circle by a random value. It avoids the overlap, and allows to make the circle layer insightful.

Here is a suggestion to implement it:

const allCircles = groupData.map((value, i) => (
   <circle
     key={i}
     cx={
@@ -11,4 +11,4 @@
     fill="grey"
     fillOpacity={0.3}
   />
-));

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +));

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/circle-packing-with-d3-force.html b/example/circle-packing-with-d3-force.html index 9a81998f..33ce584a 100644 --- a/example/circle-packing-with-d3-force.html +++ b/example/circle-packing-with-d3-force.html @@ -1,4 +1,4 @@ -Circle Packing with d3-force.

Circle Packing with d3-force

Dataviz logo representing a CircularPacking chart.

This tutorial is a variation around the general introduction to circle packing with react and d3.js. You should probably understand the concepts described there before reading here.

Instead of relying on the pack() function of d3.js to compute the best node positions, this example suggests to rely on the d3-force plugin to apply physical forces on each node.

A code sandbox is provided for the final result, but explanations target what's different compared to a classic circular packing based on some concepts described in the network diagram section.

Useful links

Plot and code

Here is the final plot we're trying to achieve here, together with its code:πŸ™‡β€β™‚οΈ

It is a circular packing chart where all circles represent an item of the dataset.

  • The circle area is proportional to the value property of the data item.
  • All circles are close to each other but do not collide. They are also attracted by the y=0 horizontal axis, what aligns them horizontally

To understand how this chart works, you need the concepts described in the Network diagram and Circle pack sections.

A circle packing chart made using the d3-force plugin, with bubbles being attracted by the y=0 baseline.

Using d3-force

This example is actually a variation of a network diagram, but with no links between nodes.

Some physical forces are applied to each node to compute their position through an iterative simulation:

d3.forceSimulation(nodes)
+Circle Packing with d3-force.

Circle Packing with d3-force

Dataviz logo representing a CircularPacking chart.

This tutorial is a variation around the general introduction to circle packing with react and d3.js. You should probably understand the concepts described there before reading here.

Instead of relying on the pack() function of d3.js to compute the best node positions, this example suggests to rely on the d3-force plugin to apply physical forces on each node.

A code sandbox is provided for the final result, but explanations target what's different compared to a classic circular packing based on some concepts described in the network diagram section.

Useful links

Plot and code

Here is the final plot we're trying to achieve here, together with its code:πŸ™‡β€β™‚οΈ

It is a circular packing chart where all circles represent an item of the dataset.

  • The circle area is proportional to the value property of the data item.
  • All circles are close to each other but do not collide. They are also attracted by the y=0 horizontal axis, what aligns them horizontally

To understand how this chart works, you need the concepts described in the Network diagram and Circle pack sections.

A circle packing chart made using the d3-force plugin, with bubbles being attracted by the y=0 baseline.

Using d3-force

This example is actually a variation of a network diagram, but with no links between nodes.

Some physical forces are applied to each node to compute their position through an iterative simulation:

d3.forceSimulation(nodes)
   .force(
     'collide',
     d3.forceCollide().radius((node) => sizeScale(node.value) + 1)
@@ -7,4 +7,4 @@
   .force('center', d3.forceCenter(width / 2, height / 2))
   .force('charge', d3.forceY(0).strength(0.05))

Here is a reminder:

  • collide avoids circle overlap. It uses each node radius to make sure there is no collision.
  • manyBody makes sure that nodes are attracted one to each other since the strength in use is positive.
  • forceCenter center the whole chart on the canvas.
  • forceY aligns bubble on a horizontal line.

Bubble Size

As explained in the bubble chart section, it is very important to have the bubble area being proportional to the numericvalue of the data point.

It is a very common mistake to make the radius proportional to numeric value, which leads to a misleading visualization.

Fortunately, it is very straightforward to scale the bubble appropriately thanks to the scaleSqrt() function.

const sizeScale = scaleSqrt()
   .domain([min, max])
-  .range([BUBBLE_MIN_SIZE, BUBBLE_MAX_SIZE]);

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file + .range([BUBBLE_MIN_SIZE, BUBBLE_MAX_SIZE]);

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/histogram-mirror.html b/example/histogram-mirror.html index 3b1f4721..16220c4c 100644 --- a/example/histogram-mirror.html +++ b/example/histogram-mirror.html @@ -1,4 +1,4 @@ -How to build a mirror histogram with React and D3.

Mirror histogram

Dataviz logo representing a Histogram chart.

This tutorial is a variation around the general introduction to histogram with react and d3.js. You should probably understand the concepts described there before reading here.

This example explains how to compare the distribution of 2 groups using amirror histogram. One group is displayed above the X axis, the other onebelow. It allows a direct comparison without having any overlap.

A code sandbox is provided for the final result, but explanations target what's different compared to an usual histogram.

Useful links

Plot and code

If you are in a hurry, this is what we're trying to achieve here.πŸ™‡β€β™‚οΈ

The distributions of 2 groups are displayed on the same figure, 1 group being on top and the other being below the X axis. It allows to compare them efficiently, with no overlap. .

02468101202468

A mirror histogram made with react and d3.js to compare the distribution of 2 groups in a dataset

The Data

The dataset used here is slightly different as the one used for the simple 1 group histogram.

An array is used, with each object in it providing the name (group property here) and the values of a group. Note that if more than 2 items are available in the array, only the 2 first will be used by the component.

Here is a minimal example of the data structure:

const data = [
+How to build a mirror histogram with React and D3.

Mirror histogram

Dataviz logo representing a Histogram chart.

This tutorial is a variation around the general introduction to histogram with react and d3.js. You should probably understand the concepts described there before reading here.

This example explains how to compare the distribution of 2 groups using amirror histogram. One group is displayed above the X axis, the other onebelow. It allows a direct comparison without having any overlap.

A code sandbox is provided for the final result, but explanations target what's different compared to an usual histogram.

Useful links

Plot and code

If you are in a hurry, this is what we're trying to achieve here.πŸ™‡β€β™‚οΈ

The distributions of 2 groups are displayed on the same figure, 1 group being on top and the other being below the X axis. It allows to compare them efficiently, with no overlap. .

02468101202468

A mirror histogram made with react and d3.js to compare the distribution of 2 groups in a dataset

The Data

The dataset used here is slightly different as the one used for the simple 1 group histogram.

An array is used, with each object in it providing the name (group property here) and the values of a group. Note that if more than 2 items are available in the array, only the 2 first will be used by the component.

Here is a minimal example of the data structure:

const data = [
   {
     group: "A",
     values: [0, 0, 2, 2, 2, 0]
@@ -17,4 +17,4 @@
 }, [xScale]);
 
 const bucketsTop = bucketGenerator(data[0].values);
-const bucketsBottom = bucketGenerator(data[1].values);

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +const bucketsBottom = bucketGenerator(data[1].values);

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/histogram-small-multiple.html b/example/histogram-small-multiple.html index 0806188b..ee54e2aa 100644 --- a/example/histogram-small-multiple.html +++ b/example/histogram-small-multiple.html @@ -1,4 +1,4 @@ -How to build a small multiple histogram with React and D3 to show the distribution of several groups.

Histogram

Dataviz logo representing a Histogram chart.

This tutorial is a variation around the general introduction to histogram with react and d3.js. You should probably understand the concepts described there before reading here.

This example explains how to plot the distribution of several groups, each distribution being drawn on its own pannel. This dataviz technique is called small multiples. It can be useful to compare the distribution of several items in a dataset.

A code sandbox is provided for the final result, but explanations target what's different compared to an usual histogram.

Useful links

Plot and code

If you are in a hurry, this is what we're trying to achieve here.πŸ™‡β€β™‚οΈ

The distribution of several groups are displayed, one on each panel of the graphing window. It allows to compare the distributions.

Note that this works even if groups have very similar distributions as the bars won't overlap each other. It is thus a very good alternative to the histogram with multiple groups that would get unreadable in this condition.

Histogram representing the distribution of 4 groups in a dataset using the small multiple display. Made with react (rendering) and d3.js (scales)

The Data

The dataset used here is slightly different as the one used for the simple 1 group histogram.

An array is used, with each object in it providing the name (group property here) and the values of a group.

Here is a minimal example of the data structure:

const data = [
+How to build a small multiple histogram with React and D3 to show the distribution of several groups.

Histogram

Dataviz logo representing a Histogram chart.

This tutorial is a variation around the general introduction to histogram with react and d3.js. You should probably understand the concepts described there before reading here.

This example explains how to plot the distribution of several groups, each distribution being drawn on its own pannel. This dataviz technique is called small multiples. It can be useful to compare the distribution of several items in a dataset.

A code sandbox is provided for the final result, but explanations target what's different compared to an usual histogram.

Useful links

Plot and code

If you are in a hurry, this is what we're trying to achieve here.πŸ™‡β€β™‚οΈ

The distribution of several groups are displayed, one on each panel of the graphing window. It allows to compare the distributions.

Note that this works even if groups have very similar distributions as the bars won't overlap each other. It is thus a very good alternative to the histogram with multiple groups that would get unreadable in this condition.

Histogram representing the distribution of 4 groups in a dataset using the small multiple display. Made with react (rendering) and d3.js (scales)

The Data

The dataset used here is slightly different as the one used for the simple 1 group histogram.

An array is used, with each object in it providing the name (group property here) and the values of a group.

Here is a minimal example of the data structure:

const data = [
   {
     group: "A",
     values: [0, 0, 2, 2, 2, 0]
@@ -48,4 +48,4 @@
       ))}
     </div>
   );
-};

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +};

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/histogram-with-several-groups.html b/example/histogram-with-several-groups.html index 3ad55640..d7825f02 100644 --- a/example/histogram-with-several-groups.html +++ b/example/histogram-with-several-groups.html @@ -1,4 +1,4 @@ -How to build a histogram with React and D3.

Histogram

Dataviz logo representing a Histogram chart.

This tutorial is a variation around the general introduction to histogram with react and d3.js. You should probably understand the concepts described there before reading here.

This example explains how to plot several groups on the same histogram, by overlapping them on the same X axis. It can be useful to compare the distribution of several items in a dataset.

A code sandbox is provided for the final result, but explanations target what's different compared to an usual histogram.

Useful links

Plot and code

If you are in a hurry, this is what we're trying to achieve here.πŸ™‡β€β™‚οΈ

The distribution of several groups are displayed on the same figure, allowing to easily compare them. Please note that this kind of visual works well when there is a clear distinction between groups. Otherwise, bars will overlap each other resulting in an unreadable chart.

Histogram representing the distribution of 3 groups in a dataset. Made with react (rendering) and d3.js (scales)

The Data

The dataset used here is slightly different as the one used for the simple 1 group histogram.

An array is used, with each object in it providing the name (group property here) and the values of a group.

Here is a minimal example of the data structure:

const data = [
+How to build a histogram with React and D3.

Histogram

Dataviz logo representing a Histogram chart.

This tutorial is a variation around the general introduction to histogram with react and d3.js. You should probably understand the concepts described there before reading here.

This example explains how to plot several groups on the same histogram, by overlapping them on the same X axis. It can be useful to compare the distribution of several items in a dataset.

A code sandbox is provided for the final result, but explanations target what's different compared to an usual histogram.

Useful links

Plot and code

If you are in a hurry, this is what we're trying to achieve here.πŸ™‡β€β™‚οΈ

The distribution of several groups are displayed on the same figure, allowing to easily compare them. Please note that this kind of visual works well when there is a clear distinction between groups. Otherwise, bars will overlap each other resulting in an unreadable chart.

Histogram representing the distribution of 3 groups in a dataset. Made with react (rendering) and d3.js (scales)

The Data

The dataset used here is slightly different as the one used for the simple 1 group histogram.

An array is used, with each object in it providing the name (group property here) and the values of a group.

Here is a minimal example of the data structure:

const data = [
   {
     group: "A",
     values: [0, 0, 2, 2, 2, 0]
@@ -47,4 +47,4 @@
       height={boundsHeight - yScale(bucket.length)}
     />
   ))
-);

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +);

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/line-chart-synchronized-cursors.html b/example/line-chart-synchronized-cursors.html index dbebfa17..55127774 100644 --- a/example/line-chart-synchronized-cursors.html +++ b/example/line-chart-synchronized-cursors.html @@ -1,4 +1,4 @@ -Line charts with synchronized cursors.

Line charts

Dataviz logo representing a Line chart.

This tutorial is a variation around the general introduction to line chart with react and d3.js. You should probably understand the concepts described there before reading here.

This example explains how to create several line charts and add asynchronized cursor on all of them. Hovering over one graph will display a cursor on all of them, easing the understanding of synchronized patterns.

A code sandbox is provided for the final result, but explanations target what's different compared to an usual line chart.

Useful links

Plot and code

If you are in a hurry, this is what we're trying to achieve here.πŸ™‡β€β™‚οΈ

Two line charts are displayed one next to each other. It shows the evolution of 2 numeric valriables.

Hovering over a chart will display a cursor that is synced with the other chart. This helps finding a relationship between them.

Hover over a chart to see a cursor on both of them, easing the time comparison.

The Data

Two dataset are used here. Both with the same format as described in theline chart section of the gallery.

Here is a minimal example of the data structure:

const data = [
+Line charts with synchronized cursors.

Line charts

Dataviz logo representing a Line chart.

This tutorial is a variation around the general introduction to line chart with react and d3.js. You should probably understand the concepts described there before reading here.

This example explains how to create several line charts and add asynchronized cursor on all of them. Hovering over one graph will display a cursor on all of them, easing the understanding of synchronized patterns.

A code sandbox is provided for the final result, but explanations target what's different compared to an usual line chart.

Useful links

Plot and code

If you are in a hurry, this is what we're trying to achieve here.πŸ™‡β€β™‚οΈ

Two line charts are displayed one next to each other. It shows the evolution of 2 numeric valriables.

Hovering over a chart will display a cursor that is synced with the other chart. This helps finding a relationship between them.

Hover over a chart to see a cursor on both of them, easing the time comparison.

The Data

Two dataset are used here. Both with the same format as described in theline chart section of the gallery.

Here is a minimal example of the data structure:

const data = [
   {x:1, y: 90},
   {x: 2, y: 12},
   {x: 3, , y: 34},
@@ -20,4 +20,4 @@
   const closest = getClosestPoint(mouseX);
 
   setCursorPosition(xScale(closest.x));
-};

Animated cursor

I used react spring to animate the cursor transition. When the mouse moves, the cursor position does not change instantly but moves smoothly to the new position.

Animation in dataviz using React is a big topic. It's impossible to go in-depth here! I will publish a dedicated blog post on the topic soon. Please subscribe to the newsletter if you want to be notified.

Hover over a chart to see a cursor on both of them, easing the time comparison.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +};

Animated cursor

I used react spring to animate the cursor transition. When the mouse moves, the cursor position does not change instantly but moves smoothly to the new position.

Animation in dataviz using React is a big topic. It's impossible to go in-depth here! I will publish a dedicated blog post on the topic soon. Please subscribe to the newsletter if you want to be notified.

Hover over a chart to see a cursor on both of them, easing the time comparison.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/network-diagram-with-colored-groups.html b/example/network-diagram-with-colored-groups.html index aca19747..fb8dbd6c 100644 --- a/example/network-diagram-with-colored-groups.html +++ b/example/network-diagram-with-colored-groups.html @@ -1,7 +1,7 @@ -Force-directed Network diagram with React and D3.js.

Force-directed Network diagram with React and D3.js

Dataviz logo representing a Network chart.

This tutorial is a variation around the general introduction to network diagram with react and d3.js. You should probably understand the concepts described there before reading here, notably everything related to the d3-force plugin.

This example shows how to apply the concepts of the general tutorial to a real dataset. It creates a force-directed graph that describes the network of character co-occurrence in Les MisΓ©rables.

A code sandbox is provided for the final result, but explanations target what's different compared to a classic network diagram.

Useful links

Plot and code

If you are in a hurry, here is the final plot we're trying to achieve here, together with its code:πŸ™‡β€β™‚οΈ

In this network diagram, each node is a character of the book Les MisΓ©rables. The network chart tries to localise characters who often appear together close to each other.

The dataset comes from this Observable version that uses d3.js only.

Network section

A network diagram made with d3.js and react. It shows the character co-occurence in Les MisΓ©rables.

Color Palette

The only difference with the very simple network chart of the mainnetwork tutorial is the presence of a color palette used to color the nodes.

Each node of the dataset is attributed to a group. It is thus possible to create a color scale using a scaleOrdinal:

// List of Groups
+Force-directed Network diagram with React and D3.js.

Force-directed Network diagram with React and D3.js

Dataviz logo representing a Network chart.

This tutorial is a variation around the general introduction to network diagram with react and d3.js. You should probably understand the concepts described there before reading here, notably everything related to the d3-force plugin.

This example shows how to apply the concepts of the general tutorial to a real dataset. It creates a force-directed graph that describes the network of character co-occurrence in Les MisΓ©rables.

A code sandbox is provided for the final result, but explanations target what's different compared to a classic network diagram.

Useful links

Plot and code

If you are in a hurry, here is the final plot we're trying to achieve here, together with its code:πŸ™‡β€β™‚οΈ

In this network diagram, each node is a character of the book Les MisΓ©rables. The network chart tries to localise characters who often appear together close to each other.

The dataset comes from this Observable version that uses d3.js only.

Network section

A network diagram made with d3.js and react. It shows the character co-occurence in Les MisΓ©rables.

Color Palette

The only difference with the very simple network chart of the mainnetwork tutorial is the presence of a color palette used to color the nodes.

Each node of the dataset is attributed to a group. It is thus possible to create a color scale using a scaleOrdinal:

// List of Groups
 const allGroups = [...new Set(nodes.map((d) => d.group))];
 
 // Color scale
 const colorScale = scaleOrdinal()
   .domain(allGroups)
-  .range(schemeCategory10);

Here I am using the schemeCategory10 color scale to avoid defining those color by hand.

Once the color scale is ready, it is straightforward to call it for each node in the drawNetwork() function.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file + .range(schemeCategory10);

Here I am using the schemeCategory10 color scale to avoid defining those color by hand.

Once the color scale is ready, it is straightforward to call it for each node in the drawNetwork() function.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/radar-chart-animation.html b/example/radar-chart-animation.html index cb2a2605..d7aef35a 100644 --- a/example/radar-chart-animation.html +++ b/example/radar-chart-animation.html @@ -1,4 +1,4 @@ -Types of Data Professionals

Types of Data Professionals

Dataviz logo representing a Spider chart.

The field of data offers a diverse array of job titles, making it challenging to navigate without getting lost in the jargon and uncertainty about which roles to pursue.

The charts below offer deeper insights into the competencies needed, salary ranges, and popularity trends for the four primary job titles.

It's a good opportunity to learn how to make a little application with React and D3.js, featuring 3 inter-connected chart types with smooth animated transition: radar chart, line chart and lollipop.

Useful links

The plot

Here is what we want to build. It is highly inspired by a work from Kevin Rosamont Prombo.

Four buttons are provided, one for each type of data professional. Clicking on it will update the 3 following charts.


Types of Data Professionals

The field of data offers a diverse array of job titles, making it challenging to navigate without getting lost in the jargon and uncertainty about which roles to pursue. The charts below offer deeper insights into the competencies needed, salary ranges, and popularity trends for the four primary job titles.

ML OpsData PipelinesDatabaseData VizStorytellingBusiness InsightsReportingExperimentationStatsML ModelingDeployment
00

Dive deep into the 4 main types of Data Professionals. Understand their main required competencies, their salary ranges and their popularity.

Data

The radar chart explains what competencies are required to be a Data Engineer, a Machine Learning Engineer, a Data Scientist or a Data Analyst. The data and the representation have been first suggested by Kevin Rosamont Prombo.

The little lollipop plot provides the estimated salary range for the job. Data from review n prep and glassdoor.

The line chart gives an estimate of the job popularity based on its google trend score in the last ~10 years.

Click the Show code button above to get a sandbox with the 3 datasets at json format.

Global state

The first thing that is required here is a global state.

The root file of the application computes all the available groups in the dataset (allGroups) and use the first group to state the initial state of the application.

const allGroups = data.map((d) => d.name);
+Types of Data Professionals

Types of Data Professionals

Dataviz logo representing a Spider chart.

The field of data offers a diverse array of job titles, making it challenging to navigate without getting lost in the jargon and uncertainty about which roles to pursue.

The charts below offer deeper insights into the competencies needed, salary ranges, and popularity trends for the four primary job titles.

It's a good opportunity to learn how to make a little application with React and D3.js, featuring 3 inter-connected chart types with smooth animated transition: radar chart, line chart and lollipop.

Useful links

The plot

Here is what we want to build. It is highly inspired by a work from Kevin Rosamont Prombo.

Four buttons are provided, one for each type of data professional. Clicking on it will update the 3 following charts.


Types of Data Professionals

The field of data offers a diverse array of job titles, making it challenging to navigate without getting lost in the jargon and uncertainty about which roles to pursue. The charts below offer deeper insights into the competencies needed, salary ranges, and popularity trends for the four primary job titles.

ML OpsData PipelinesDatabaseData VizStorytellingBusiness InsightsReportingExperimentationStatsML ModelingDeployment
00

Dive deep into the 4 main types of Data Professionals. Understand their main required competencies, their salary ranges and their popularity.

Data

The radar chart explains what competencies are required to be a Data Engineer, a Machine Learning Engineer, a Data Scientist or a Data Analyst. The data and the representation have been first suggested by Kevin Rosamont Prombo.

The little lollipop plot provides the estimated salary range for the job. Data from review n prep and glassdoor.

The line chart gives an estimate of the job popularity based on its google trend score in the last ~10 years.

Click the Show code button above to get a sandbox with the 3 datasets at json format.

Global state

The first thing that is required here is a global state.

The root file of the application computes all the available groups in the dataset (allGroups) and use the first group to state the initial state of the application.

const allGroups = data.map((d) => d.name);
 const [selectedGroup, setSelectedGroup] = useState(allGroups[0]);

When the user clicks a button, the state is updated thanks to the setSelectedGroup() function. The newly selected group (selectedGroup) is then passed to the graphing component as a prop.

Charts

Then we need to build 3 charts based on the 3 filtered dataset.

The React graph gallery already provides in-depth tutorials for those 3 chart types. So please refer to the radar chart, line chart and lollipop sections to learn how to build them.


Animation

Most of the fun here comes from the smooth, animated transition between groups. It is also the trickiest part to implement.

As always in this gallery, the animation is computed thanks to react-spring, a javascript library for spring animation in React.

It would be way too long to explain how to implement it properly in this page. But to put it in a nutshell, you need to render animated elements instead of usual SVG elements. Here is how the line is rendered for instance:

const LineItem = ({ path, color }: LineItemProps) => {
   const springProps = useSpring({
     to: {
@@ -18,4 +18,4 @@
       strokeWidth={2}
     />
   );
-};

I plan to write some complete tutorials on this passionating and complicated topic. You can subscribe to the project to know when it's ready!

Subscribe

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +};

I plan to write some complete tutorials on this passionating and complicated topic. You can subscribe to the project to know when it's ready!

Subscribe

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/scatterplot-basic-canvas.html b/example/scatterplot-basic-canvas.html index fca97c85..4721cf8b 100644 --- a/example/scatterplot-basic-canvas.html +++ b/example/scatterplot-basic-canvas.html @@ -1,4 +1,4 @@ -Scatterplot with Canvas

Scatterplot with Canvas

Dataviz logo representing a ScatterPlot chart.

This tutorial is a variation around the general introduction to scatterplot with react and d3.js. You should probably understand the concepts described there before reading here.

Rendering a scatterplot using SVG can arm the performance of your webpage if the number of data points is high. A common workaround is to draw the circles in canvas instead.

This post explains how to combine SVG for the axes and canvas for the scatterplot markers in React.

Useful links

Why using canvas? πŸ€”

A scatterplot is a chart type that is commonly used to display a high amount of data points.

When you draw it in SVG, it means adding a bunch of circle elements. As a result, your DOM will quickly become really heavy. It can result in poor performances. If you want to add some animation on top of it, you are pretty sure to freeze the page.

When using canvas, you add only 1 node in your DOM, and benefit the very high speed of it. It is game changer for any viz type that requires good performances.

Scatterplot canvas implementation

The trick here is to use 2 layers of drawing:

  • The first layer is for the axes. It is an SVG element that will add the X and Y axes using some usual AxisLeft and AxisBottom components.
  • The second layer is for the markers, it is the canvas element. It has a ref. We can then call a function in a useEffect hook to draw inside this canvas element.

This is how the useEffect hook looks like, drawing our circles:

useEffect(() => {
+Scatterplot with Canvas

Scatterplot with Canvas

Dataviz logo representing a ScatterPlot chart.

This tutorial is a variation around the general introduction to scatterplot with react and d3.js. You should probably understand the concepts described there before reading here.

Rendering a scatterplot using SVG can arm the performance of your webpage if the number of data points is high. A common workaround is to draw the circles in canvas instead.

This post explains how to combine SVG for the axes and canvas for the scatterplot markers in React.

Useful links

Why using canvas? πŸ€”

A scatterplot is a chart type that is commonly used to display a high amount of data points.

When you draw it in SVG, it means adding a bunch of circle elements. As a result, your DOM will quickly become really heavy. It can result in poor performances. If you want to add some animation on top of it, you are pretty sure to freeze the page.

When using canvas, you add only 1 node in your DOM, and benefit the very high speed of it. It is game changer for any viz type that requires good performances.

Scatterplot canvas implementation

The trick here is to use 2 layers of drawing:

  • The first layer is for the axes. It is an SVG element that will add the X and Y axes using some usual AxisLeft and AxisBottom components.
  • The second layer is for the markers, it is the canvas element. It has a ref. We can then call a function in a useEffect hook to draw inside this canvas element.

This is how the useEffect hook looks like, drawing our circles:

useEffect(() => {
   const canvas = canvasRef.current;
 
   if (!canvas) {
@@ -17,4 +17,4 @@
     ctx.fillStyle = '#cb1dd1';
     ctx.fill();
   });
-}, [data, xScale, yScale, width, height]);

Here is a complete implementation of the scatterplot using this technique with 10000 data points:

0246810121416

A scatterplot made with React, using SVG for the axes and Canvas for the markers to improve performance.



Canvas is an important topic in data visualization for the web. I plan to write complete articles on the topic. You can know when it's ready by subscribing to the project.

Tell me when the canvas post is ready!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}, [data, xScale, yScale, width, height]);

Here is a complete implementation of the scatterplot using this technique with 10000 data points:

0246810121416

A scatterplot made with React, using SVG for the axes and Canvas for the markers to improve performance.



Canvas is an important topic in data visualization for the web. I plan to write complete articles on the topic. You can know when it's ready by subscribing to the project.

Tell me when the canvas post is ready!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/scatterplot-tooltip-with-voronoi-for-closest-point-detection.html b/example/scatterplot-tooltip-with-voronoi-for-closest-point-detection.html index 7779f55f..5db7d20a 100644 --- a/example/scatterplot-tooltip-with-voronoi-for-closest-point-detection.html +++ b/example/scatterplot-tooltip-with-voronoi-for-closest-point-detection.html @@ -1,5 +1,5 @@ -Scatterplot tooltip with React and D3: use Voronoi to detect closest point.

Scatterplot tooltip: use Voronoi for closest point detection

Dataviz logo representing a ScatterPlot chart.

This tutorial is a variation around the general introduction to scatterplot with react and d3.js. You should probably understand the concepts described there before reading here.

This example explains how to use an invisible Voronoi diagram in the background to detect the mouse closest point of the scatterplot.

A code sandbox is provided for the final result, but explanations target what's different compared to an usual scatter plot.

Useful links

Plot and code

If you are in a hurry, this is what we're trying to achieve here.πŸ™‡β€β™‚οΈ

This is a scatterplot with voronoi detection. When you enter the chart area with your mouse, the closest point is found using a Delaunay triangulation. The corresponding circle is highlighted on the chart.

Same concept could easily be used to add a tooltip with great performance.

A scatterplot with tooltip. The closest point is detected using Voronoi to trigger the tooltip apparition.

The Data

The dataset used here is the same as for an usual scatterplot.

It is an array of objects where each object is a data point. The object can have many properties, but at least a x and a y prop are needed to provide the 2d coordinates.

Here is a minimal example of the data structure:

const data = [
+Scatterplot tooltip with React and D3: use Voronoi to detect closest point.

Scatterplot tooltip: use Voronoi for closest point detection

Dataviz logo representing a ScatterPlot chart.

This tutorial is a variation around the general introduction to scatterplot with react and d3.js. You should probably understand the concepts described there before reading here.

This example explains how to use an invisible Voronoi diagram in the background to detect the mouse closest point of the scatterplot.

A code sandbox is provided for the final result, but explanations target what's different compared to an usual scatter plot.

Useful links

Plot and code

If you are in a hurry, this is what we're trying to achieve here.πŸ™‡β€β™‚οΈ

This is a scatterplot with voronoi detection. When you enter the chart area with your mouse, the closest point is found using a Delaunay triangulation. The corresponding circle is highlighted on the chart.

Same concept could easily be used to add a tooltip with great performance.

A scatterplot with tooltip. The closest point is detected using Voronoi to trigger the tooltip apparition.

The Data

The dataset used here is the same as for an usual scatterplot.

It is an array of objects where each object is a data point. The object can have many properties, but at least a x and a y prop are needed to provide the 2d coordinates.

Here is a minimal example of the data structure:

const data = [
   { x: 10, y: 10 },
   { x: 4, y: 4 },
   ...
-];

Building the Voronoi diagram

The shapes drawn in the background are called a Voronoi diagram.

A voronoi diagram is a is a partition of a plane into regions called voronoi cells. A voronoi cell consists of every point in the plane whose distance to its linked data point is less than or equal to its distance to any other data point.

This is very handy to detect the mouse closest point on a scatterplot! πŸ”₯

The react graph gallery has a dedicated section on the topic. Once you understood how Voronoi works with d3, it is just a matter of adding axes to get a scatterplot with point detection.

Voronoi section

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +];

Building the Voronoi diagram

The shapes drawn in the background are called a Voronoi diagram.

A voronoi diagram is a is a partition of a plane into regions called voronoi cells. A voronoi cell consists of every point in the plane whose distance to its linked data point is less than or equal to its distance to any other data point.

This is very handy to detect the mouse closest point on a scatterplot! πŸ”₯

The react graph gallery has a dedicated section on the topic. Once you understood how Voronoi works with d3, it is just a matter of adding axes to get a scatterplot with point detection.

Voronoi section

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/example/timeseries-moving-average.html b/example/timeseries-moving-average.html index 21fdccd4..a04fc4c6 100644 --- a/example/timeseries-moving-average.html +++ b/example/timeseries-moving-average.html @@ -1,4 +1,4 @@ -Timeseries with moving average

Timeseries with moving average

Dataviz logo representing a Time chart.

In this tutorial, we'll explore the art of plotting time series data, incorporating a dynamic moving average line chart overlaid on the primary plot.

Inspired by a visualization featured in the renowned French newspaper Le Monde, depicting the blooming patterns of cherry trees over time, we'll recreate this compelling chart.

With readily available code and straightforward explanations, you'll witness the prowess of React in seamlessly stacking multiple layers of rendering – from scatterplots to line charts and annotations.

Useful links

πŸ‡―πŸ‡΅ Poetry in Data

Amidst the myriad visualizations of global warming, one stands out for its poetic resonance – an unexpected gem found within the pages of a French newspaper: the flourishing timelines of cherry trees in Japan.

Intriguingly, Yasuyuki Aono delved into ancient texts dating back to the 800s to unearth this data. Thanks to the meticulous efforts of Our World in Data in cleaning and refining the dataset, we're now presented with a captivating portrayal of our changing world.


Here is the chart we're learning to build today:

Plein floraison annuelleMoyenne de la floraison (20 ans)
1950 - 202316 Mars21 Mars26 Mars31 Mars5 Avril10 Avril15 Avril20 Avril25 Avril30 Avril5 Mai90010001100120013001400150016001700180019002000

Prerequisite

This graph combines elements of both a scatterplot and a line chart, making it essential to grasp the fundamentals of each chart type before diving in.

Good news, the react graph gallery has some very basic examples to illustrate those concepts!

Most basic scatterplot made with react and d3

Basic scatter plot

Add circles to get a basic scatter plot

Picture of a very simple line chart made with react and d3

Most basic line chart

The most basic line chart one can make using d3 and react

Annotation

The deepest layer of this chart is the annotation that says 1950 - 2023. It uses stripes in the background. Stripes can be build in SVG as follow:

<defs>
+Timeseries with moving average

Timeseries with moving average

Dataviz logo representing a Time chart.

In this tutorial, we'll explore the art of plotting time series data, incorporating a dynamic moving average line chart overlaid on the primary plot.

Inspired by a visualization featured in the renowned French newspaper Le Monde, depicting the blooming patterns of cherry trees over time, we'll recreate this compelling chart.

With readily available code and straightforward explanations, you'll witness the prowess of React in seamlessly stacking multiple layers of rendering – from scatterplots to line charts and annotations.

Useful links

πŸ‡―πŸ‡΅ Poetry in Data

Amidst the myriad visualizations of global warming, one stands out for its poetic resonance – an unexpected gem found within the pages of a French newspaper: the flourishing timelines of cherry trees in Japan.

Intriguingly, Yasuyuki Aono delved into ancient texts dating back to the 800s to unearth this data. Thanks to the meticulous efforts of Our World in Data in cleaning and refining the dataset, we're now presented with a captivating portrayal of our changing world.


Here is the chart we're learning to build today:

Plein floraison annuelleMoyenne de la floraison (20 ans)
1950 - 202316 Mars21 Mars26 Mars31 Mars5 Avril10 Avril15 Avril20 Avril25 Avril30 Avril5 Mai90010001100120013001400150016001700180019002000

Prerequisite

This graph combines elements of both a scatterplot and a line chart, making it essential to grasp the fundamentals of each chart type before diving in.

Good news, the react graph gallery has some very basic examples to illustrate those concepts!

Most basic scatterplot made with react and d3

Basic scatter plot

Add circles to get a basic scatter plot

Picture of a very simple line chart made with react and d3

Most basic line chart

The most basic line chart one can make using d3 and react

Annotation

The deepest layer of this chart is the annotation that says 1950 - 2023. It uses stripes in the background. Stripes can be build in SVG as follow:

<defs>
   <pattern
     id="pattern_annotation"
     patternUnits="userSpaceOnUse"
@@ -43,4 +43,4 @@
       </g>
     ))}
   </>
-);

Full code

Let's wrap this up!

The full code for this chart is available below. Click the Show Code button.

Plein floraison annuelleMoyenne de la floraison (20 ans)
1950 - 202316 Mars21 Mars26 Mars31 Mars5 Avril10 Avril15 Avril20 Avril25 Avril30 Avril5 Mai

Reproduction of a chart published in the newspaper Le Monde.

Going further

This graph looks pretty good. A few potential improvements:

  • Add a tooltip to give more information about each data point
  • Use Voronoi for closest point detection to trigger the hover effect

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +);

Full code

Let's wrap this up!

The full code for this chart is available below. Click the Show Code button.

Plein floraison annuelleMoyenne de la floraison (20 ans)
1950 - 202316 Mars21 Mars26 Mars31 Mars5 Avril10 Avril15 Avril20 Avril25 Avril30 Avril5 Mai

Reproduction of a chart published in the newspaper Le Monde.

Going further

This graph looks pretty good. A few potential improvements:

  • Add a tooltip to give more information about each data point
  • Use Voronoi for closest point detection to trigger the hover effect

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/fix-canvas-blurry-dataviz.html b/fix-canvas-blurry-dataviz.html index 1a1ff78e..65e08ecb 100644 --- a/fix-canvas-blurry-dataviz.html +++ b/fix-canvas-blurry-dataviz.html @@ -1 +1 @@ -Fixing the blurry canvas on retina screens

Fixing the blurry canvas on retina screens


Drawing a chart on a canvas element instead of using svg elements can be a huge performance boost. However, it leads to a blurry and unreadable viz on retina screens if the resolution is not taken into account. Here is how to fix.

-⬜ Pixel, Resolution and DPI

To understand why a canvas can get blurry on a retina screen, you first need to have some basic knowledge about how an image is displayed on a screen.

Screens are made up of thousands of tiny dots all bunched together called pixels. Each pixel has the ability to change its color. The total number of pixels on a screen differs from one monitor to another, we call it the screen resolution. If the screen has 1,024 pixels horizontally, and 768 vertically it has a 'resolution' of 1,024 x 768.

A screen is a set of pixels

When you watch dataviz-inspiration.com on your screen, you actually watch thousands of pixels.

It's important to understand that 2 screens with the same physical size (let's say 30 inches) can have very different amount of pixels. The density of pixels on a screen is called DPI for dots per inch or ppi for pixels per inch.

Retina screens have a very high DPI, and it is where our troubbles begin

-↕️ Physical vs CSS resolution

Let's say that you create a html element and give it a width of 100px using css. This is the css width. If you use a screen that has a very high resolution, pixels are very very small. As a result, your element of 100px would appear very small too on the screen.

To avoid this, each monitor applies a pixel ratio. On a retina screen this ratio equals 2. When you ask the monitor to draw an element of 100px, it will actually draw it with a length of 200px. This is the physical width.

In javascript, you can access this ratio with window.devicePixelRatio and here is the complete doc about it.

-πŸ› Canvas, High-DPI and the bug

Let's add a canvas element in our DOM, with a width of 100px. It is the equivalent of building an image, 100px wide, that we insert in the DOM.

If we display the result on a retina screen with a devicePixelRatio of 2, the image will be scaled up to 200px wide. The browser will interpolate pixels to make the image bigger, and it results in a blurry output.

To avoid this issue, we the canvas we're creating must be twice bigger on retina screen

A pixelated output when an image is scaled up

A small img or canvas on a retina screen will be scaled up, resulting in a pixelated / blurry output.

-πŸ€¦β€β™‚οΈ The 2 dimensions of the canvas element

There are 2 different ways to control the dimension of a canvas element.

  • width and height attributes: They control the size of the image that is created and inserted in the DOM.
    Default to 300px and 150px so always specify them.
  • css style: the canvas element can be styled using CSS. As a result we can also pass a width and a height here. It controls the size of the element on the screen.

Here is a html code snippet illustrating this concept:

<canvas style="width:200px; height:200px;" width="100px" height="100px">

Now, let's play with those 2 values to see what happens. In the examples below, a segment going from 0,0 (top left) to 100,100 is drawn.

β†’ Small image, big output

If I create a small image with my canvas (100x100) and output it in big (300x300), the browser has to scale it up to display it, resulting in a blurry output

<canvas style="width:300px; height:300px;" width="100px" height="100px">

This is exactly what happens when you display a canvas on a retina screen πŸ™€.

β†’ Big image, small output

Now I create a big image with my canvas (200x200) and output it in small (100x100), the browser has to scale it down to display it, β†’ crispy output!

<canvas style="width:100px; height:100px;" width="200px" height="200px">

Much better. But my diagonal is now wrong since it goes to 100,100, which is half way to 200,200. Fortunately javascript is here to the rescue. I will just have to use the scale function to automatically correct those coordinates.

-πŸ”¨ Fixing the Canvas and Retina screens issue

To finally fix the retina bug, we need to:

  • Control the size of the canvas output using the css dimension
  • Find the device pixel ratio using window.devicePixelRatio
  • Create a bigger canvas image if the pixel ratio is over 1. This is done thanks to the width and height attributes.
  • Use the scale() function in our canvas context to correct our coordinates

Here are 2 examples. The first one does not apply the correction (left). The second does the correction (right)

On retina screens, the left shape is blurry when the right one is not.

To see the full code of those 2 examples, click the buttons below.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +Fixing the blurry canvas on retina screens

Fixing the blurry canvas on retina screens


Drawing a chart on a canvas element instead of using svg elements can be a huge performance boost. However, it leads to a blurry and unreadable viz on retina screens if the resolution is not taken into account. Here is how to fix.

-⬜ Pixel, Resolution and DPI

To understand why a canvas can get blurry on a retina screen, you first need to have some basic knowledge about how an image is displayed on a screen.

Screens are made up of thousands of tiny dots all bunched together called pixels. Each pixel has the ability to change its color. The total number of pixels on a screen differs from one monitor to another, we call it the screen resolution. If the screen has 1,024 pixels horizontally, and 768 vertically it has a 'resolution' of 1,024 x 768.

A screen is a set of pixels

When you watch dataviz-inspiration.com on your screen, you actually watch thousands of pixels.

It's important to understand that 2 screens with the same physical size (let's say 30 inches) can have very different amount of pixels. The density of pixels on a screen is called DPI for dots per inch or ppi for pixels per inch.

Retina screens have a very high DPI, and it is where our troubbles begin

-↕️ Physical vs CSS resolution

Let's say that you create a html element and give it a width of 100px using css. This is the css width. If you use a screen that has a very high resolution, pixels are very very small. As a result, your element of 100px would appear very small too on the screen.

To avoid this, each monitor applies a pixel ratio. On a retina screen this ratio equals 2. When you ask the monitor to draw an element of 100px, it will actually draw it with a length of 200px. This is the physical width.

In javascript, you can access this ratio with window.devicePixelRatio and here is the complete doc about it.

-πŸ› Canvas, High-DPI and the bug

Let's add a canvas element in our DOM, with a width of 100px. It is the equivalent of building an image, 100px wide, that we insert in the DOM.

If we display the result on a retina screen with a devicePixelRatio of 2, the image will be scaled up to 200px wide. The browser will interpolate pixels to make the image bigger, and it results in a blurry output.

To avoid this issue, we the canvas we're creating must be twice bigger on retina screen

A pixelated output when an image is scaled up

A small img or canvas on a retina screen will be scaled up, resulting in a pixelated / blurry output.

-πŸ€¦β€β™‚οΈ The 2 dimensions of the canvas element

There are 2 different ways to control the dimension of a canvas element.

  • width and height attributes: They control the size of the image that is created and inserted in the DOM.
    Default to 300px and 150px so always specify them.
  • css style: the canvas element can be styled using CSS. As a result we can also pass a width and a height here. It controls the size of the element on the screen.

Here is a html code snippet illustrating this concept:

<canvas style="width:200px; height:200px;" width="100px" height="100px">

Now, let's play with those 2 values to see what happens. In the examples below, a segment going from 0,0 (top left) to 100,100 is drawn.

β†’ Small image, big output

If I create a small image with my canvas (100x100) and output it in big (300x300), the browser has to scale it up to display it, resulting in a blurry output

<canvas style="width:300px; height:300px;" width="100px" height="100px">

This is exactly what happens when you display a canvas on a retina screen πŸ™€.

β†’ Big image, small output

Now I create a big image with my canvas (200x200) and output it in small (100x100), the browser has to scale it down to display it, β†’ crispy output!

<canvas style="width:100px; height:100px;" width="200px" height="200px">

Much better. But my diagonal is now wrong since it goes to 100,100, which is half way to 200,200. Fortunately javascript is here to the rescue. I will just have to use the scale function to automatically correct those coordinates.

-πŸ”¨ Fixing the Canvas and Retina screens issue

To finally fix the retina bug, we need to:

  • Control the size of the canvas output using the css dimension
  • Find the device pixel ratio using window.devicePixelRatio
  • Create a bigger canvas image if the pixel ratio is over 1. This is done thanks to the width and height attributes.
  • Use the scale() function in our canvas context to correct our coordinates

Here are 2 examples. The first one does not apply the correction (left). The second does the correction (right)

On retina screens, the left shape is blurry when the right one is not.

To see the full code of those 2 examples, click the buttons below.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/heatmap.html b/heatmap.html index 70951885..e043b8c2 100644 --- a/heatmap.html +++ b/heatmap.html @@ -1,4 +1,4 @@ -How to build a heatmap with React and D3.

Heatmap

Dataviz logo representing a Heatmap chart.

A heat map (or heatmap) is a chart type that shows the magnitude of a numeric variable as a color in two dimensions. This page is a step-by-step guide on how to build your own heatmap for the web, using React and D3.js.

It starts by describing how the data should be organized and potentially normalized. It then shows how to initialize the heatmap component, build band scales and add rectangles to get a first heatmap. Last but not least, responsiveness and the tooltip are described in depth and a real dataset is used to get a heatmap application. πŸ™‡β€β™‚οΈ.

Useful links

The Data

The dataset is usually an array where each item provides information for a cell of the heatmap.

Each item is an object that requires at least a value property that is a number. This number will be used to color the cell.

Each item also requires an x and a y property, providing the position of the cell in the 2-d space. Note that those values are strings since anything can be used. We are dealing with ordinal scales here.

Note that you can add any kind of information to those cell objects. Such information can be included in tooltips later on.


Here is a minimal example of the data structure:

const data = [
+How to build a heatmap with React and D3.

Heatmap

Dataviz logo representing a Heatmap chart.

A heat map (or heatmap) is a chart type that shows the magnitude of a numeric variable as a color in two dimensions. This page is a step-by-step guide on how to build your own heatmap for the web, using React and D3.js.

It starts by describing how the data should be organized and potentially normalized. It then shows how to initialize the heatmap component, build band scales and add rectangles to get a first heatmap. Last but not least, responsiveness and the tooltip are described in depth and a real dataset is used to get a heatmap application. πŸ™‡β€β™‚οΈ.

Useful links

The Data

The dataset is usually an array where each item provides information for a cell of the heatmap.

Each item is an object that requires at least a value property that is a number. This number will be used to color the cell.

Each item also requires an x and a y property, providing the position of the cell in the 2-d space. Note that those values are strings since anything can be used. We are dealing with ordinal scales here.

Note that you can add any kind of information to those cell objects. Such information can be included in tooltips later on.


Here is a minimal example of the data structure:

const data = [
   { x: 'A', y: 'A', value: 12 },
   { x: 'B', y: 'A', value: 2 },
   { x: 'C', y: 'A', value: 9 }
@@ -52,7 +52,7 @@
       fill={colorScale(d.value)}
     />
   );
-});

Note that for the X and Y axis labels, just adding a set of svg text element does a pretty good job, so no need to build complicated axis components as for a scatterplot.


ABCDEFGHIJABCDE

Most basic heatmap made with react and d3.js. d3 is used to compute scales, react for the rendering.

That's it, we have a first good looking heatmap!

The process used to build it with react is pretty close from building it with d3.js only. (Check the pure d3 implementation here).

Responsive Heatmap with react

The component above is not responsive. It expects 2 props called width and height and will render a Heatmap of those dimensions.

Making the Heatmap responsive requires adding a wrapper component that gets the dimension of the parent div, and listening to a potential dimension change. This is possible thanks to a hook called useDimensions that will do the job for us.

useDimensions: a hook to make your viz responsive
export const useDimensions = (targetRef: React.RefObject<HTMLDivElement>) => {
+});

Note that for the X and Y axis labels, just adding a set of svg text element does a pretty good job, so no need to build complicated axis components as for a scatterplot.


ABCDEFGHIJABCDE

Most basic heatmap made with react and d3.js. d3 is used to compute scales, react for the rendering.

That's it, we have a first good looking heatmap!

The process used to build it with react is pretty close from building it with d3.js only. (Check the pure d3 implementation here).

Responsive Heatmap with react

The component above is not responsive. It expects 2 props called width and height and will render a Heatmap of those dimensions.

Making the Heatmap responsive requires adding a wrapper component that gets the dimension of the parent div, and listening to a potential dimension change. This is possible thanks to a hook called useDimensions that will do the job for us.

useDimensions: a hook to make your viz responsive
export const useDimensions = (targetRef: React.RefObject<HTMLDivElement>) => {
 
   const getDimensions = () => {
     return {
@@ -80,7 +80,7 @@
 }

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Tooltip

Adding a tooltip is an important improvement for a heatmap. It allows us to get as much detail as needed for each cell.

There are many different approaches to building tooltips, and I'm preparing a whole dedicated blog post on the topic.

In the example below I suggest using the same strategy as for scatterplots. So you probably want to read it there for an in-depth explanation.

β†’ Two layers: renderer and tooltip

The first task is to split the Heatmap component into 2 layers. The first layer called Renderer will render the cells as seen previously. The second is an absolute div put on top of the first one, used only to show the tooltip div.

This way, the x and y coordinates of cells in the first layer match with the coordinate of the second layer.

<div style={{ position: "relative" }}>
   <Renderer ..someProps />
   <Tooltip ..someProps />
-</div>

β†’ A common state

On top of the 2 layers, we need a state that stores information about the cell being hovered over. You can create it with a useState statement. I usually call it interactionData in this website.

This state is passed to the Tooltip layer. The function to update it (the "setter") is passed to the Renderer layer. When the user hovers over a cell, this setter is triggered to update the state and thus the tooltip.

const [hoveredCell, setHoveredCell] = useState<InteractionData | null>(null);

β†’ Hover, update state, render tooltips

The heatmap cells listen to onMouseEnter events and update the tooltip state (hoveredCell) with accurate coordinates when it happens.

This state is passed to the Tooltip component. It renders a div at the right position thanks to the information. A bit of smart css is used to make it pretty and include a little arrow.

ABCDEFGHIJABCDE

This heatmap has a tooltip. Hover over a cell to get its exact value.

There is much more to say about tooltips but hopefully that should get you started. Subscribe to the gallery, I'll post more on this topic soon.

Heatmap inspiration

If you're looking for inspiration to create your next Heatmap, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Heatmap looks good!

visit

Color legend

A heatmap uses a color scale to encode a numeric value into a color. As a result, it is very much advised to add a color legend to explicit how this color scale works.

Let's consider a variable that goes from 0 to 100. We want to encode 0 in blue and 100 in purple. The color scale is built thanks to the scaleLinear() function of d3 as described above.

const [hoveredCell, setHoveredCell] = useState<InteractionData | null>(null);

β†’ Hover, update state, render tooltips

The heatmap cells listen to onMouseEnter events and update the tooltip state (hoveredCell) with accurate coordinates when it happens.

This state is passed to the Tooltip component. It renders a div at the right position thanks to the information. A bit of smart css is used to make it pretty and include a little arrow.

ABCDEFGHIJABCDE

This heatmap has a tooltip. Hover over a cell to get its exact value.

There is much more to say about tooltips but hopefully that should get you started. Subscribe to the gallery, I'll post more on this topic soon.

Heatmap inspiration

If you're looking for inspiration to create your next Heatmap, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Heatmap looks good!

visit

Color legend

A heatmap uses a color scale to encode a numeric value into a color. As a result, it is very much advised to add a color legend to explicit how this color scale works.

Let's consider a variable that goes from 0 to 100. We want to encode 0 in blue and 100 in purple. The color scale is built thanks to the scaleLinear() function of d3 as described above.

020406080100

A color legend built with react, canvas and d3.

The trick here is to create a canvas element of the desired width and height. Then, loop from left to right and add one rectangle for each pixel with the corresponding color using the same color scale as the one used on the chart. It's important to do it in canvas: you don't want to add 300 elements in your DOM if your legend is 300px wide.

Once the canvas element is instantiated with a ref, you can draw the color scale thanks to a useEffect like this:

useEffect(() => {
   const canvas = canvasRef.current;
   const context = canvas?.getContext("2d");
@@ -95,4 +95,4 @@
     context.fillRect(i, 0, 1, height);
   }
 }, [width, height, colorScale]);

Then you probably want to add some ticks on top of the color graduation to make it insightful.

Fortunately, the d3 linearScale comes with a handy tick() function. Basically, calling xScale.ticks(4) will create an array with approximately 4 items, each providing everything you need to draw a smartly located tick.

Color Legend is a big topic. There is much more to say about it and I'll post a complete blog post on the topic soon. Subscribe to the gallery if interested!

Application to a real dataset

This is an application of the heatmap component described above to a real life dataset.

It's actually a recreation of this chart by Tynan DeBold and Dov Friedman. Data was available here. Chart was originally made with highcharts, original code being here.

It was necessary to tweak the color scale, switching to a square transformation with scaleSequentialSqrt. This allows to give less importance the extreme values that would absorb the variation otherwise.

193019401950196019701980199020002010AlaskaArk.Calif.Conn.Del.Ga.IowaIll.Kan.La.Md.Mich.Mo.Mont.N.D.N.H.N.MN.Y.Okla.Pa.S.C.Tenn.UtahVt.Wis.Wyo.
0k1k2k

Number of Measles infected people over 70-some years and across all 50 states. Can you guess when a vaccine was introduced?

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file + 0px">0k1k2k

Number of Measles infected people over 70-some years and across all 50 states. Can you guess when a vaccine was introduced?

Correlation

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/hexbin-map.html b/hexbin-map.html index 9d292d55..17b5b3b9 100644 --- a/hexbin-map.html +++ b/hexbin-map.html @@ -1,4 +1,4 @@ -How to build a hexbin map component with React and D3.

Hexbin Map

Dataviz logo representing a MapHexbin chart.

A hexbin map is a visual representation of data that aggregates individual data points into hexagonal bins or cells, typically used for spatial analysis. It helps to condense large datasets and identify patterns or trends within specific geographic regions.

Two types of hexbin map exist. The first one is based on a geoJsonfile that provides the hexagon boundaries. It is similar to a choropleth map, with hexagons instead of real regions. The second is actually a 2d density chart, but with GPS locations for the x and y coordinates.

This page is a long form tutorial explaining how to build hexbin maps using react and d3.js. It provides interactive examples for both types of hexbin maps with code explanation and should get you started for your web app.

Useful links

Hexbin map from a geoJson file

Drawing a map using react and d3.js usually relies on a geoJson file. This file format provides information for geographical regions. It stores the 2d coordinates of shapes.

This is the way it looks:

{
+How to build a hexbin map component with React and D3.

Hexbin Map

Dataviz logo representing a MapHexbin chart.

A hexbin map is a visual representation of data that aggregates individual data points into hexagonal bins or cells, typically used for spatial analysis. It helps to condense large datasets and identify patterns or trends within specific geographic regions.

Two types of hexbin map exist. The first one is based on a geoJsonfile that provides the hexagon boundaries. It is similar to a choropleth map, with hexagons instead of real regions. The second is actually a 2d density chart, but with GPS locations for the x and y coordinates.

This page is a long form tutorial explaining how to build hexbin maps using react and d3.js. It provides interactive examples for both types of hexbin maps with code explanation and should get you started for your web app.

Useful links

Hexbin map from a geoJson file

Drawing a map using react and d3.js usually relies on a geoJson file. This file format provides information for geographical regions. It stores the 2d coordinates of shapes.

This is the way it looks:

{
   "type": "FeatureCollection",
   "features": [
       {
@@ -102,4 +102,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Hexbin inspiration

If you're looking for inspiration to create your next Hexbin, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Hexbin looks good!

visit

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Hexbin inspiration

If you're looking for inspiration to create your next Hexbin, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Hexbin looks good!

visit

Map

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/hierarchical-edge-bundling.html b/hierarchical-edge-bundling.html index 1b0d7cb4..9d4b1ff0 100644 --- a/hierarchical-edge-bundling.html +++ b/hierarchical-edge-bundling.html @@ -1,4 +1,4 @@ -Hierarchical Edge Bundling | React Graph Gallery

Hierarchical edge bundling

Dataviz logo representing a Bundle chart.

A hierarchical edge bundling chart allows to visualize relationships between entities organized in a hierarchy. The idea is to bundle the adjacency edges together to decrease the clutter usually observed in complex networks.

This page explains how to build a hierarchical edge bundling chart using d3.js to compute the node position, and React to render the nodes and edges. It starts by describing the required data format, explains how to build a very basic hierarchical edge bundling and then shows how to customize it.

Useful links

The Data

The dataset describes a hierarchy using a recursive structure.

Each item in this structure is called a node. The lowest nodes of the hierarchy being called leaves.

The dataset is an object that has at least 3 properties: name, value and children. children is an array of nodes that have this structure too.

This kind of data is very close to what's required for a dendrogram. But an additional property is added for the leaves: links. It provides a list of all the other leaves this leaf is connected with.

Here is a minimal example of the data structure:

const data = {
+Hierarchical Edge Bundling | React Graph Gallery

Hierarchical edge bundling

Dataviz logo representing a Bundle chart.

A hierarchical edge bundling chart allows to visualize relationships between entities organized in a hierarchy. The idea is to bundle the adjacency edges together to decrease the clutter usually observed in complex networks.

This page explains how to build a hierarchical edge bundling chart using d3.js to compute the node position, and React to render the nodes and edges. It starts by describing the required data format, explains how to build a very basic hierarchical edge bundling and then shows how to customize it.

Useful links

The Data

The dataset describes a hierarchy using a recursive structure.

Each item in this structure is called a node. The lowest nodes of the hierarchy being called leaves.

The dataset is an object that has at least 3 properties: name, value and children. children is an array of nodes that have this structure too.

This kind of data is very close to what's required for a dendrogram. But an additional property is added for the leaves: links. It provides a list of all the other leaves this leaf is connected with.

Here is a minimal example of the data structure:

const data = {
   type: 'node',
   name: "boss",
   value: 2300,
@@ -44,4 +44,4 @@
         />
       );
     });
-  });

Resulting in our first hierarchical edge bundling example πŸŽ‰

MarkRobertEmilyMarionEdyGabYanNicolasMalkiDjΓ©JoeKarlMamTotoTuckYamMΓ©lanieEinstein

A first hierarchical edge bundling chart made with d3 and react.

Coming soon

Using canvas for rendering is often a requirement when the number of nodes gets big. Interactivity is often necessary, for hover effect or to collapse a part of the tree. It also possible to map the node circle size to a numeric variable.

This will come soon! I have a newsletter called the dataviz universe where I share my latest updates.

Subscribe

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file + });

Resulting in our first hierarchical edge bundling example πŸŽ‰

MarkRobertEmilyMarionEdyGabYanNicolasMalkiDjΓ©JoeKarlMamTotoTuckYamMΓ©lanieEinstein

A first hierarchical edge bundling chart made with d3 and react.

Coming soon

Using canvas for rendering is often a requirement when the number of nodes gets big. Interactivity is often necessary, for hover effect or to collapse a part of the tree. It also possible to map the node circle size to a numeric variable.

This will come soon! I have a newsletter called the dataviz universe where I share my latest updates.

Subscribe

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/histogram.html b/histogram.html index e68e2293..445c6314 100644 --- a/histogram.html +++ b/histogram.html @@ -1,4 +1,4 @@ -How to build a histogram with React and D3.

Histogram

Dataviz logo representing a Histogram chart.

A histogram is a chart type that shows the distribution of a numeric variable. This page is a step-by-step guide on how to build your own histogram for the web, using React and D3.js.

It starts by describing how the data should be organized and how to initialize the histogram component. It then explains how to compute the buckets composing the histogram. Once this is done, it shows how to render the bars and suggests a few variations. πŸ™‡β€β™‚οΈ.

Useful links

The Data

Building a histogram only requires a set of numeric values.

As a result, the dataset is pretty simple: an array of numbers.


Here is a minimal example of the data structure:

const data = [1, 2, 2, 2, 3, 4, 5, 6, 6, 6, 9]

Component skeleton

The goal here is to create a Histogram component that will be stored in a Histogram.tsx file. This component requires 3 props to render: a width, a height, and some data.

The shape of the data is described above. The width and height will be used to render an svg element in the DOM, in which we will insert the histogram.

To put it in a nutshell, that's the skeleton of our Histogram component:

import * as d3 from "d3"; // we will need d3.js
+How to build a histogram with React and D3.

Histogram

Dataviz logo representing a Histogram chart.

A histogram is a chart type that shows the distribution of a numeric variable. This page is a step-by-step guide on how to build your own histogram for the web, using React and D3.js.

It starts by describing how the data should be organized and how to initialize the histogram component. It then explains how to compute the buckets composing the histogram. Once this is done, it shows how to render the bars and suggests a few variations. πŸ™‡β€β™‚οΈ.

Useful links

The Data

Building a histogram only requires a set of numeric values.

As a result, the dataset is pretty simple: an array of numbers.


Here is a minimal example of the data structure:

const data = [1, 2, 2, 2, 3, 4, 5, 6, 6, 6, 9]

Component skeleton

The goal here is to create a Histogram component that will be stored in a Histogram.tsx file. This component requires 3 props to render: a width, a height, and some data.

The shape of the data is described above. The width and height will be used to render an svg element in the DOM, in which we will insert the histogram.

To put it in a nutshell, that's the skeleton of our Histogram component:

import * as d3 from "d3"; // we will need d3.js
 
 type HistogramProps = {
   width: number;
@@ -82,7 +82,7 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Histogram inspiration

If you're looking for inspiration to create your next Histogram, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Histogram looks good!

visit

Variations

Once you've understood how to build a basic histogram with d3 and react, it opens an infinite world of customization. Here are a few examples showing how to add several groups on the same axis or how to use small multiple with histograms to compare distributions.

Click on the overview below to get details and code.


picture of a mirror histogram made with react and d3.js

Mirror histogram

Create a mirror histogram to compare the distribution of 2 groups in a dataset

Picture of a histogram with small multiple built with react and d3.js

Small multiple

Create one panel per group to show its distribution separately

Picture of a histogram with multiple groups built with react and d3.js

Multiple groups

A histogram with <b>multiple</b> groups displayed on the same axis.

Dataset transition

The last step needed for a powerful histogram React component is a proper way to transition between various datasets. When the data prop updates, we need a stunning way to transition to the new values.

There are many different strategies to approach this problem. I suggest to rely on the react-spring library that has everything we need to compute spring animations.

Instead of rendering usual rect elements, the library provides a animated.rect element, that is linked to a useSpringhook.

A histogram that smoothly transition from 1 dataset to another

This is how the Rectangle component I use looks like:

Rectangle: a component that animates the transition of a rect
import { useSpring, animated } from "@react-spring/web";
+}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Histogram inspiration

If you're looking for inspiration to create your next Histogram, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Histogram looks good!

visit

Variations

Once you've understood how to build a basic histogram with d3 and react, it opens an infinite world of customization. Here are a few examples showing how to add several groups on the same axis or how to use small multiple with histograms to compare distributions.

Click on the overview below to get details and code.


picture of a mirror histogram made with react and d3.js

Mirror histogram

Create a mirror histogram to compare the distribution of 2 groups in a dataset

Picture of a histogram with small multiple built with react and d3.js

Small multiple

Create one panel per group to show its distribution separately

Picture of a histogram with multiple groups built with react and d3.js

Multiple groups

A histogram with <b>multiple</b> groups displayed on the same axis.

Dataset transition

The last step needed for a powerful histogram React component is a proper way to transition between various datasets. When the data prop updates, we need a stunning way to transition to the new values.

There are many different strategies to approach this problem. I suggest to rely on the react-spring library that has everything we need to compute spring animations.

Instead of rendering usual rect elements, the library provides a animated.rect element, that is linked to a useSpringhook.

A histogram that smoothly transition from 1 dataset to another

This is how the Rectangle component I use looks like:

Rectangle: a component that animates the transition of a rect
import { useSpring, animated } from "@react-spring/web";
 
 type RectangleProps = {
   width: number;
@@ -120,4 +120,4 @@
       rx={1}
     />
   );
-};

Animation in dataviz using React is a big topic. It's impossible to go in depth here! I will publish a dedicated blog post on the topic soon. Please subscribe to the newsletter if you want to be notified.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +};

Animation in dataviz using React is a big topic. It's impossible to go in depth here! I will publish a dedicated blog post on the topic soon. Please subscribe to the newsletter if you want to be notified.

Distribution

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/index.html b/index.html index a4d65572..29942738 100644 --- a/index.html +++ b/index.html @@ -1 +1 @@ -Learn to build unique charts with React

Build unique React charts


Have you ever wanted to create your own chart for the web?

Based on hundreds of graph examples, this gallery guides you through the basic concepts of data visualization with React and D3.js. It also provides ready-to-use templates to get started quicker.

Stop using pre-made dataviz components β†’ imagination will become the only boundary to your creativity.

The gallery is organized by chart types following the data-to-viz classification.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +Learn to build unique charts with React

Build unique React charts


Have you ever wanted to create your own chart for the web?

Based on hundreds of graph examples, this gallery guides you through the basic concepts of data visualization with React and D3.js. It also provides ready-to-use templates to get started quicker.

Stop using pre-made dataviz components β†’ imagination will become the only boundary to your creativity.

The gallery is organized by chart types following the data-to-viz classification.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/interactivity.html b/interactivity.html index 83c4f0ef..82b8e6fd 100644 --- a/interactivity.html +++ b/interactivity.html @@ -1 +1 @@ -Interactivity

Interactivity

Dataviz logo representing a Interactive chart.

Interactivity is a key feature of any chart displayed on the web. It includes tooltip, hover effect, cross-graph interaction, zooming, panning and more.

Interactivity is a big topic. This section aims at giving general tips and tricks on the topic together with applied examples ready to be used in your project.

Useful links

Work in Progress

This section is a work in progress. 🚧

For now, it just lists all the charts using Interactivity in the gallery.

But I plan to write some complete tutorials on this passionating and complicated topic. You can subscribe to the project to know when it's ready!


Subscribe


GIF of a scatterplot with hover effect

Scatterplot Hover effect

How to add a hover effect to highlight a group on a scatterplot

GIF of a bubble plot smoothly transitioning data

Bubble plot data set transition

How to smoothly animate the transition between dataset

gif of a violin plot smoothly transitioning to a boxplot using shape morphism

Violin to Boxplot transition

Using shape morphism to smoothly transition from a boxplot to a violin and reverse

GIF showing a violin plot with varying bucket size

Bucket size effect

Interactive example showing the bucket size effect on a violin chart

GIF showing a mirror transition between a boxplot and a violin plot

Boxplot to Violin plot

Interactive example showing the difference between a boxplot and a violin

GIF of a histogram with animated data transition

Histogram dataset transition

How to animate the transition between datasets

GIF of a data update on a React barplot

Barplot dataset transition

How to smoothly animate the transition between dataset

GIF of a line chart that animates between 2 dataset

Line chart with dataset transition

How to smoothly animate the transition between 2 dataset on a line chart

GIF of a streamgraph react component that supports hover effect

Streamgraph with hover effect

How to add a hover effect on a streamgraph to highlight a group

GIF of a streamgraph

Offset and Smoothing transition

An interactive streamgraph example showing how to animate transition between the chart stacking features.

GIF of a streamgraph with multiple interactive features

Streamgraph application

Streamgraph with a slider to zoom on a time stamp and with interactive inline legends

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +Interactivity

Interactivity

Dataviz logo representing a Interactive chart.

Interactivity is a key feature of any chart displayed on the web. It includes tooltip, hover effect, cross-graph interaction, zooming, panning and more.

Interactivity is a big topic. This section aims at giving general tips and tricks on the topic together with applied examples ready to be used in your project.

Useful links

Work in Progress

This section is a work in progress. 🚧

For now, it just lists all the charts using Interactivity in the gallery.

But I plan to write some complete tutorials on this passionating and complicated topic. You can subscribe to the project to know when it's ready!


Subscribe


GIF of a scatterplot with hover effect

Scatterplot Hover effect

How to add a hover effect to highlight a group on a scatterplot

GIF of a bubble plot smoothly transitioning data

Bubble plot data set transition

How to smoothly animate the transition between dataset

gif of a violin plot smoothly transitioning to a boxplot using shape morphism

Violin to Boxplot transition

Using shape morphism to smoothly transition from a boxplot to a violin and reverse

GIF showing a violin plot with varying bucket size

Bucket size effect

Interactive example showing the bucket size effect on a violin chart

GIF showing a mirror transition between a boxplot and a violin plot

Boxplot to Violin plot

Interactive example showing the difference between a boxplot and a violin

GIF of a histogram with animated data transition

Histogram dataset transition

How to animate the transition between datasets

GIF of a data update on a React barplot

Barplot dataset transition

How to smoothly animate the transition between dataset

GIF of a line chart that animates between 2 dataset

Line chart with dataset transition

How to smoothly animate the transition between 2 dataset on a line chart

GIF of a streamgraph react component that supports hover effect

Streamgraph with hover effect

How to add a hover effect on a streamgraph to highlight a group

GIF of a streamgraph

Offset and Smoothing transition

An interactive streamgraph example showing how to animate transition between the chart stacking features.

GIF of a streamgraph with multiple interactive features

Streamgraph application

Streamgraph with a slider to zoom on a time stamp and with interactive inline legends

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/line-chart.html b/line-chart.html index 52aca28f..f315aa26 100644 --- a/line-chart.html +++ b/line-chart.html @@ -1,4 +1,4 @@ -Line chart | The React Graph Gallery

Line chart

Dataviz logo representing a Line chart.

A line chart or line graph displays the evolution of one or several numeric variables. This page is a step-by-step guide on how to build your own line chart component for the web, using React and D3.js.

It starts by describing how the data should be organized and how to initialize the react component. It then explains how to compute the scales, and axes. Once this is done, it shows how to render the lines and suggests a few variations. πŸ™‡β€β™‚οΈ.

Useful links

The Data

The dataset required to build a line chart is usually an array where each item is an object providing the x and the y values of the data point.


Here is a minimal example:

const data = [
+Line chart | The React Graph Gallery

Line chart

Dataviz logo representing a Line chart.

A line chart or line graph displays the evolution of one or several numeric variables. This page is a step-by-step guide on how to build your own line chart component for the web, using React and D3.js.

It starts by describing how the data should be organized and how to initialize the react component. It then explains how to compute the scales, and axes. Once this is done, it shows how to render the lines and suggests a few variations. πŸ™‡β€β™‚οΈ.

Useful links

The Data

The dataset required to build a line chart is usually an array where each item is an object providing the x and the y values of the data point.


Here is a minimal example:

const data = [
   {x:1, y: 90},
   {x: 2, y: 12},
   {x: 3, y: 34},
@@ -90,4 +90,4 @@
       strokeWidth={2}
     />
   );
-};

Click on the buttons to trigger a smooth transition between the 2 line charts.

Animation in dataviz using React is a big topic. It's impossible to go in-depth here! I will publish a dedicated blog post on the topic soon. Please subscribe to the newsletter if you want to be notified.

Variations

You now have the basic understanding on how to build a basic line chart component with React and d3.js. Below are a few examples showing how to build more complex graphs based on those principles.

GIF of a radar chart, a line chart and a lollipop that animate between dataset

Radar chart, line chart an lollipop with animated transition

Three charts connected to same buttons, with smooth, synchronized animation when a button is clicked

line charts with synchronized cursors

Synchronized cursors

Add a cursor synchronized on all your charts

Picture of a timeseries chart made with React and D3.js: scatterplot and line chart in use.

Timeseries with moving average

A scatterplot used for timeseries, with the moving average shown as a line chart on top.

Next

The react graph gallery is under heavy development. Here is a list of things that will be added soon.

ToDoHow to add a tooltip
ToDoMulti groups line charts aka Spaghetti chart
ToDoSync with a bar chart
ToDoDual Y Axis
ToDoInline legend with Reppel


Subscribe to the gallery to know when it is ready!

Subscribe


Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +};

Click on the buttons to trigger a smooth transition between the 2 line charts.

Animation in dataviz using React is a big topic. It's impossible to go in-depth here! I will publish a dedicated blog post on the topic soon. Please subscribe to the newsletter if you want to be notified.

Variations

You now have the basic understanding on how to build a basic line chart component with React and d3.js. Below are a few examples showing how to build more complex graphs based on those principles.

GIF of a radar chart, a line chart and a lollipop that animate between dataset

Radar chart, line chart an lollipop with animated transition

Three charts connected to same buttons, with smooth, synchronized animation when a button is clicked

line charts with synchronized cursors

Synchronized cursors

Add a cursor synchronized on all your charts

Picture of a timeseries chart made with React and D3.js: scatterplot and line chart in use.

Timeseries with moving average

A scatterplot used for timeseries, with the moving average shown as a line chart on top.

Next

The react graph gallery is under heavy development. Here is a list of things that will be added soon.

ToDoHow to add a tooltip
ToDoMulti groups line charts aka Spaghetti chart
ToDoSync with a bar chart
ToDoDual Y Axis
ToDoInline legend with Reppel


Subscribe to the gallery to know when it is ready!

Subscribe


Evolution

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/lollipop-plot.html b/lollipop-plot.html index abe66d93..0469e446 100644 --- a/lollipop-plot.html +++ b/lollipop-plot.html @@ -1,4 +1,4 @@ -Lollipop plot with React

Lollipop plot

Dataviz logo representing a Lollipop chart.

A lollipop plot is a variation of the more common barplot. This page is a step-by-step guide on how to build your own lollipop for the web, using React and D3.js.

It starts by describing how the data should be organized and how to initialize the lollipop component. It explains how to build the scales and axes and how to add the shapes. A few variations are described and a focus is made on the hover interaction. πŸ™‡β€β™‚οΈ.

Useful links

The Data

The dataset required to build a lollipop is usually an array where each item is an object providing the name and the value of the group.


Here is a minimal example:

const data = [
+Lollipop plot with React

Lollipop plot

Dataviz logo representing a Lollipop chart.

A lollipop plot is a variation of the more common barplot. This page is a step-by-step guide on how to build your own lollipop for the web, using React and D3.js.

It starts by describing how the data should be organized and how to initialize the lollipop component. It explains how to build the scales and axes and how to add the shapes. A few variations are described and a focus is made on the hover interaction. πŸ™‡β€β™‚οΈ.

Useful links

The Data

The dataset required to build a lollipop is usually an array where each item is an object providing the name and the value of the group.


Here is a minimal example:

const data = [
   {name:"Mark", value: 90},
   {name:"Robert", value: 12},
   {name:"Emily", value: 34},
@@ -65,4 +65,4 @@
 /* Except for the specific row that is hovered hover that keeps its opacity to 1 */
 .rowsContainer .row:hover {
   opacity: 1;
-}

β†’ For the second effect, 2 svg rectangles must be drawn. The first one fills the full width and height of the row. It is the one that triggers the mouse event. (It is important to remember that a svg g element does not trigger mouse events. Only what is drawn inside it does). The second rectangle is the one that we see. We can add some vertical padding to it since it is not use for mouse detection.

20406080100NicolasMarkMarionEmilyMΓ©lanieGabrielRobertPaul

Try to hover a row in the lollipop above to reveal the hover interaction.

Data transition

It is very common to deal with various variables and compare the behaviour of some data items for them. It adds a nice touch to the graph to smoothly transition between 2 states using a quick animation.

For the example below I rely on the react-spring library. This lib allows to quickly create spring animations using javascript. It results in a very a natural transition that can be interrupted without restarting from 0. (try to toggle between datasets quickly).

It would be too long to explain the code here. Instead, I'm currently writing a set of dedicated tutorials. Please subscribe to the newsletter to know when this will be released.

A lollipop chart with smooth transition between dataset.

Variation

Check a few other examples of the gallery involving lollipop plots:

GIF of a radar chart, a line chart and a lollipop that animate between dataset

Radar chart, line chart an lollipop with animated transition

Three charts connected to same buttons, with smooth, synchronized animation when a button is clicked


Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

β†’ For the second effect, 2 svg rectangles must be drawn. The first one fills the full width and height of the row. It is the one that triggers the mouse event. (It is important to remember that a svg g element does not trigger mouse events. Only what is drawn inside it does). The second rectangle is the one that we see. We can add some vertical padding to it since it is not use for mouse detection.

20406080100NicolasMarkMarionEmilyMΓ©lanieGabrielRobertPaul

Try to hover a row in the lollipop above to reveal the hover interaction.

Data transition

It is very common to deal with various variables and compare the behaviour of some data items for them. It adds a nice touch to the graph to smoothly transition between 2 states using a quick animation.

For the example below I rely on the react-spring library. This lib allows to quickly create spring animations using javascript. It results in a very a natural transition that can be interrupted without restarting from 0. (try to toggle between datasets quickly).

It would be too long to explain the code here. Instead, I'm currently writing a set of dedicated tutorials. Please subscribe to the newsletter to know when this will be released.

A lollipop chart with smooth transition between dataset.

Variation

Check a few other examples of the gallery involving lollipop plots:

GIF of a radar chart, a line chart and a lollipop that animate between dataset

Radar chart, line chart an lollipop with animated transition

Three charts connected to same buttons, with smooth, synchronized animation when a button is clicked


Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/make-a-graph-responsive.html b/make-a-graph-responsive.html index b28e1e2e..c2299dd8 100644 --- a/make-a-graph-responsive.html +++ b/make-a-graph-responsive.html @@ -1,4 +1,4 @@ -How to build a responsive chart with React and d3.js

How to build a responsive chart with React and d3.js


Most of the viz components of this gallery accept a width and a height property. Yet, most of the time the dimensions of the viz we're building are unknown. We just want them to fit their container. Let's build a hookthat retrieves the parent container dimension and passes it to the viz.

This density chart is responsive! try to resize your window to see how the graph fits.

-A hook to get a div's dimension

The method I use on this website to make my chart responsive uses a hook. Hooks let you use y and other React features without writing a class as explained in the doc


This hook is basically a function that checks the offsetWidth and offsetHeight of a ref that is provided as input.


An event listener to the resize event is added to the window, to make sure the dimension is updated when the window size changes.


That's how the hook looks like:

export const useDimensions = (targetRef: React.RefObject<HTMLDivElement>) => {
+How to build a responsive chart with React and d3.js

How to build a responsive chart with React and d3.js


Most of the viz components of this gallery accept a width and a height property. Yet, most of the time the dimensions of the viz we're building are unknown. We just want them to fit their container. Let's build a hookthat retrieves the parent container dimension and passes it to the viz.

This density chart is responsive! try to resize your window to see how the graph fits.

-A hook to get a div's dimension

The method I use on this website to make my chart responsive uses a hook. Hooks let you use y and other React features without writing a class as explained in the doc


This hook is basically a function that checks the offsetWidth and offsetHeight of a ref that is provided as input.


An event listener to the resize event is added to the window, to make sure the dimension is updated when the window size changes.


That's how the hook looks like:

export const useDimensions = (targetRef: React.RefObject<HTMLDivElement>) => {
 
   const getDimensions = () => {
     return {
@@ -29,4 +29,4 @@
       height={chartSize.height}
       width={chartSize.width}
   </div>
-)

Here is an application with a ViolinPlot component that accepts a width and a height property, becoming responsive thanks to this hook:


-Caveat

Remember that the element we are tracking needs to have a height and a width. Otherwise the hook will basically return nothing.

β†’ Container is displayed as inline

An html elemente that is displayed as inline (display: inline;) cannot have a width and height. spanelements are inline by default.

β†’ By default, a div has no height

By default, the width of a div is 100%, and its height fits its content. Which means that with no content, there is no height.

β†’ Width 100% is ignored, flex example

By default, the width of a div is 100%, and its height fits its content. Which means that with no content, there is no height.

β†’ Mind the border

Josh Comeau post about border being part of the main box.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +)

Here is an application with a ViolinPlot component that accepts a width and a height property, becoming responsive thanks to this hook:


-Caveat

Remember that the element we are tracking needs to have a height and a width. Otherwise the hook will basically return nothing.

β†’ Container is displayed as inline

An html elemente that is displayed as inline (display: inline;) cannot have a width and height. spanelements are inline by default.

β†’ By default, a div has no height

By default, the width of a div is 100%, and its height fits its content. Which means that with no content, there is no height.

β†’ Width 100% is ignored, flex example

By default, the width of a div is 100%, and its height fits its content. Which means that with no content, there is no height.

β†’ Mind the border

Josh Comeau post about border being part of the main box.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/map.html b/map.html index f7d73798..875e420b 100644 --- a/map.html +++ b/map.html @@ -1,4 +1,4 @@ -How to build a background map with React and D3.

Background Map

Dataviz logo representing a Map chart.

This section is dedicated to background maps. It is the fundation required to build more interesting dataviz-related mapslike bubble maps, choropleth maps and more.

The interactive sandboxes and explanation below explain how to read a geoJson file and draw its content using React. It also show how useful the d3-geo module can be to deal with this format, notably to control the various existing projections.

Last but not least, this document also briefly explains how Leaflet can be used in a React environment to display interactive maps.

Useful links

The Data

The first thing you need to build a map is the 2d coordinates of the boundaries of the regions you want to represent. If you are trying to build a world map, you need to know where the country boundaries are located πŸ€·β€β™€οΈ.

Several formats exist to store such a piece of information. When working with d3.js, the expected format is geoJSON. A geoJSON file looks pretty much like this:


Here is a minimal example of the data structure:

{
+How to build a background map with React and D3.

Background Map

Dataviz logo representing a Map chart.

This section is dedicated to background maps. It is the fundation required to build more interesting dataviz-related mapslike bubble maps, choropleth maps and more.

The interactive sandboxes and explanation below explain how to read a geoJson file and draw its content using React. It also show how useful the d3-geo module can be to deal with this format, notably to control the various existing projections.

Last but not least, this document also briefly explains how Leaflet can be used in a React environment to display interactive maps.

Useful links

The Data

The first thing you need to build a map is the 2d coordinates of the boundaries of the regions you want to represent. If you are trying to build a world map, you need to know where the country boundaries are located πŸ€·β€β™€οΈ.

Several formats exist to store such a piece of information. When working with d3.js, the expected format is geoJSON. A geoJSON file looks pretty much like this:


Here is a minimal example of the data structure:

{
   "type": "FeatureCollection",
   "features": [
     {
@@ -93,4 +93,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Map inspiration

If you're looking for inspiration to create your next Map, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Map looks good!

visit

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Map inspiration

If you're looking for inspiration to create your next Map, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Map looks good!

visit

Map

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/network-chart.html b/network-chart.html index 3f5e2eac..7de4bc66 100644 --- a/network-chart.html +++ b/network-chart.html @@ -1,4 +1,4 @@ -How to build a Network Diagram with React and D3.

Network diagram

Dataviz logo representing a Network chart.

A network diagram shows the interconnections between entities. It is consituted by nodes that represent entities and by links that show relationships between entities.

This page is a step by step tutorial explaining how to build a network diagram component with React and D3.js. It relies on the d3-force plugin to compute the node positions. It comes with explanations and code sandboxes. It starts by simple concepts like how to format the data and how to draw nodes and links in SVG, and then goes further with hover effect, tooltip and more.

Useful links

The Data

Two layers of information are required to build a network diagram: a list of nodes to build the circles and a list of links to build the lines.

Many different data structures can be used to store such information. In this tutorial I suggest to start with the following:

export const data = {
+How to build a Network Diagram with React and D3.

Network diagram

Dataviz logo representing a Network chart.

A network diagram shows the interconnections between entities. It is consituted by nodes that represent entities and by links that show relationships between entities.

This page is a step by step tutorial explaining how to build a network diagram component with React and D3.js. It relies on the d3-force plugin to compute the node positions. It comes with explanations and code sandboxes. It starts by simple concepts like how to format the data and how to draw nodes and links in SVG, and then goes further with hover effect, tooltip and more.

Useful links

The Data

Two layers of information are required to build a network diagram: a list of nodes to build the circles and a list of links to build the lines.

Many different data structures can be used to store such information. In this tutorial I suggest to start with the following:

export const data = {
   nodes: [
       { id: "Myriel", group: 'team1' },
       { id: "Anne", group: 'team1' },
@@ -96,4 +96,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Network inspiration

If you're looking for inspiration to create your next Network, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Network looks good!

visit

Available forces

The exausthive list of forces that can be applied to nodes is available in the official documentation. Here is an overview of the main ones:

  • d3.forceManyBody() β†’ simulates attraction between nodes if its strength is positive, repulsion otherwise.

  • d3.forceCenter() β†’ translates nodes uniformly so that the mean position of all nodes is at a given position.

  • d3.forceCollide() β†’ tries to avoid node collision and overlap. You can provide a radius and a strength.

  • d3.forceLink() β†’ pushes linked nodes together or apart according to the desired link distance.

  • d3.forceX() β†’ applies a force toward a X position to all nodes. d3.forceY() is also available.
Radius used to avoid collision: 25
ManyBody strength: 0
ForceY strength: 0.1

A first network diagram built using react and d3-force.

Variations

Once you've understood how to build a basic network diagram with d3 and react, it opens an infinite world of customization. Here are a few examples using the same concepts.

Click on the overview below to get details and code.


Picture of a circle packing chart made using the d3-force plugin

Circle Pack with d3-force

Another approach to build a circle packing chart using physical forces to compute node positions.

Picture of a vertical arc diagram

Vertical arc diagram

The vertical version of the arc diagram is more convenient to display labels

Picture of a force directed network chart showing character co-occurence in les miserables

Force directed graph

A force directed network chart showing character co-occurence in les miserables

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Network inspiration

If you're looking for inspiration to create your next Network, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Network looks good!

visit

Available forces

The exausthive list of forces that can be applied to nodes is available in the official documentation. Here is an overview of the main ones:

  • d3.forceManyBody() β†’ simulates attraction between nodes if its strength is positive, repulsion otherwise.

  • d3.forceCenter() β†’ translates nodes uniformly so that the mean position of all nodes is at a given position.

  • d3.forceCollide() β†’ tries to avoid node collision and overlap. You can provide a radius and a strength.

  • d3.forceLink() β†’ pushes linked nodes together or apart according to the desired link distance.

  • d3.forceX() β†’ applies a force toward a X position to all nodes. d3.forceY() is also available.
Radius used to avoid collision: 25
ManyBody strength: 0
ForceY strength: 0.1

A first network diagram built using react and d3-force.

Variations

Once you've understood how to build a basic network diagram with d3 and react, it opens an infinite world of customization. Here are a few examples using the same concepts.

Click on the overview below to get details and code.


Picture of a circle packing chart made using the d3-force plugin

Circle Pack with d3-force

Another approach to build a circle packing chart using physical forces to compute node positions.

Picture of a vertical arc diagram

Vertical arc diagram

The vertical version of the arc diagram is more convenient to display labels

Picture of a force directed network chart showing character co-occurence in les miserables

Force directed graph

A force directed network chart showing character co-occurence in les miserables

Flow

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/parallel-plot.html b/parallel-plot.html index 60e6a728..12340bb4 100644 --- a/parallel-plot.html +++ b/parallel-plot.html @@ -1,4 +1,4 @@ -Parallel Coordinate chart | React graph gallery

Parallel coordinates

Dataviz logo representing a Parallel1 chart.

A parallel coordinate chart is a type of visualization used to represent multivariate data on a two-dimensional plane by plotting each variable as a separate axis arranged in parallel, and then connecting the data points with lines.

This page is a step-by-step guide on how to build your own parallel coordinate chart for the web, using React (for rendering) and D3.js (to compute the axis, and shape coordinates).

It starts by describing how the data should be organized and how to initialize the parallel coordinate component. It then explains how to compute axis dynamically, and plot the lines and axis. Once this is done, it shows how to deal with scaling and how to add an interactive legend. πŸ™‡β€β™‚οΈ.

Useful links

The Data

The dataset provides several numeric values for a set of data points. It can also add some categorical variables that can be added to customize the marker colors.

The suggested data structure is an array of object, where each object is a data point. It can have as many numeric properties as needed.


Here is a minimal example of the data structure:

const data = [
+Parallel Coordinate chart | React graph gallery

Parallel coordinates

Dataviz logo representing a Parallel1 chart.

A parallel coordinate chart is a type of visualization used to represent multivariate data on a two-dimensional plane by plotting each variable as a separate axis arranged in parallel, and then connecting the data points with lines.

This page is a step-by-step guide on how to build your own parallel coordinate chart for the web, using React (for rendering) and D3.js (to compute the axis, and shape coordinates).

It starts by describing how the data should be organized and how to initialize the parallel coordinate component. It then explains how to compute axis dynamically, and plot the lines and axis. Once this is done, it shows how to deal with scaling and how to add an interactive legend. πŸ™‡β€β™‚οΈ.

Useful links

The Data

The dataset provides several numeric values for a set of data points. It can also add some categorical variables that can be added to customize the marker colors.

The suggested data structure is an array of object, where each object is a data point. It can have as many numeric properties as needed.


Here is a minimal example of the data structure:

const data = [
   {var1: 5.1, var2: 3.5, ..., group: 'setosa'},
   {var1: 4.9, var2: 3.0, ..., group: 'setosa'},
   ...
@@ -81,4 +81,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Parallel inspiration

If you're looking for inspiration to create your next Parallel, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Parallel looks good!

visit

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Parallel inspiration

If you're looking for inspiration to create your next Parallel, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Parallel looks good!

visit

Ranking

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/pie-plot.html b/pie-plot.html index cbb1b4cb..05c3fc0f 100644 --- a/pie-plot.html +++ b/pie-plot.html @@ -1,4 +1,4 @@ -Pie chart with React

Pie chart

Dataviz logo representing a Pie chart.

A pie chart is a type of graph used to visually represent data as a circular, segmented chart. The chart is divided into slices, where the size of each slice represents the proportion of data that falls within a particular category or group.

This post explains how to build a pie chart with react, using the pie() function of d3.js. It describes the expected data format, how the Pie component must be structured, how to compute the slice positions and how to render those slices. Last but not least, it provides the implementation for common use-cases like hover effect and data transition.

Useful links

The Data

The dataset required to build a pie chart is pretty simple. It is an array where each item represents a group of the pie chart. Each item is an object with 2 properties. They provide the group name (name) and its value (value).


For instance, here is the dataset used for the simple pie chart below:

const data = [
+Pie chart with React

Pie chart

Dataviz logo representing a Pie chart.

A pie chart is a type of graph used to visually represent data as a circular, segmented chart. The chart is divided into slices, where the size of each slice represents the proportion of data that falls within a particular category or group.

This post explains how to build a pie chart with react, using the pie() function of d3.js. It describes the expected data format, how the Pie component must be structured, how to compute the slice positions and how to render those slices. Last but not least, it provides the implementation for common use-cases like hover effect and data transition.

Useful links

The Data

The dataset required to build a pie chart is pretty simple. It is an array where each item represents a group of the pie chart. Each item is an object with 2 properties. They provide the group name (name) and its value (value).


For instance, here is the dataset used for the simple pie chart below:

const data = [
   {name:"Mark", value: 90},
   {name:"Robert", value: 12},
   {name:"Emily", value: 34},
@@ -96,4 +96,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Pie Chart inspiration

If you're looking for inspiration to create your next Pie Chart, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Pie Chart looks good!

visit

Data transition

The Pie component expects a data prop. What should we do when this data changes?

By default, the chart will update instantly, with no transition. Adding a smooth transition gives a nice polish touch to the graph. Try to switch between the 2 datasets below to see the animation in action.

The code below relies on the react-spring library. Instead of rendering a path for each slice, it uses a animated.path component that handles the spring animation for us.

The implementation is not trivial. I plan to publish a full tutorial on react-spring for data visualization soon. You can subscribe here to be notified when it is ready.

A donut chart with clean inline legends, built thanks to the centroid function of d3.js.

Note: check the blue group that appears / disappears between dataset. This kind of enter/exit pattern is something to keep in mind when building animations.

Pie chart to barplot

Pie charts are often criticized since angles are hard to read. Let's represent the same data using a pie chart or a barplot, to see what's the most insightful πŸ€·β€β™‚οΈ.

Note that here we animate the transition between different shape types: each arc becomes a rectangle and reciprocally. This is made possible thanks to the flubber library, used in coordination with react-spring.

Once more, a full tutorial is needed here. You can subscribe here to be notified when it is ready. In the meanwhile, the code of this specific example is provided below.

Transition from a pie chart to a barplot with a smooth animation using the buttons on top.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Pie Chart inspiration

If you're looking for inspiration to create your next Pie Chart, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Pie Chart looks good!

visit

Data transition

The Pie component expects a data prop. What should we do when this data changes?

By default, the chart will update instantly, with no transition. Adding a smooth transition gives a nice polish touch to the graph. Try to switch between the 2 datasets below to see the animation in action.

The code below relies on the react-spring library. Instead of rendering a path for each slice, it uses a animated.path component that handles the spring animation for us.

The implementation is not trivial. I plan to publish a full tutorial on react-spring for data visualization soon. You can subscribe here to be notified when it is ready.

A donut chart with clean inline legends, built thanks to the centroid function of d3.js.

Note: check the blue group that appears / disappears between dataset. This kind of enter/exit pattern is something to keep in mind when building animations.

Pie chart to barplot

Pie charts are often criticized since angles are hard to read. Let's represent the same data using a pie chart or a barplot, to see what's the most insightful πŸ€·β€β™‚οΈ.

Note that here we animate the transition between different shape types: each arc becomes a rectangle and reciprocally. This is made possible thanks to the flubber library, used in coordination with react-spring.

Once more, a full tutorial is needed here. You can subscribe here to be notified when it is ready. In the meanwhile, the code of this specific example is provided below.

Transition from a pie chart to a barplot with a smooth animation using the buttons on top.

Part Of A Whole

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/radar-chart.html b/radar-chart.html index 872be59f..b6dbd9b7 100644 --- a/radar-chart.html +++ b/radar-chart.html @@ -1,4 +1,4 @@ -Radar chart | React graph gallery

Radar Chart

Dataviz logo representing a Spider chart.

A radar or spider or web chart is a two-dimensional chart type designed to plot one or more series of values over multiple quantitative variables. Each variable has its own axis, all axes are joined in the center of the figure.

This page is a step-by-step guide on how to build your own radar chart for the web, using React (for rendering) and D3.js (to compute the axis, and shape coordinates).

It starts by describing how the data should be organized and how to initialize the Radar component. It then explains how to compute axis dynamically, and plot the lines and axis. Once this is done, it shows how to deal with scaling and how to add an interactive legend. πŸ™‡β€β™‚οΈ.

Useful links

The Data

The dataset provides several numeric values for a set of data items.

The suggested data structure is an array of object, where each object is a data item. It can have as many numeric properties as needed. It also has a name property that identifies the data item.


Here is a minimal example of the data structure:

const data = [
+Radar chart | React graph gallery

Radar Chart

Dataviz logo representing a Spider chart.

A radar or spider or web chart is a two-dimensional chart type designed to plot one or more series of values over multiple quantitative variables. Each variable has its own axis, all axes are joined in the center of the figure.

This page is a step-by-step guide on how to build your own radar chart for the web, using React (for rendering) and D3.js (to compute the axis, and shape coordinates).

It starts by describing how the data should be organized and how to initialize the Radar component. It then explains how to compute axis dynamically, and plot the lines and axis. Once this is done, it shows how to deal with scaling and how to add an interactive legend. πŸ™‡β€β™‚οΈ.

Useful links

The Data

The dataset provides several numeric values for a set of data items.

The suggested data structure is an array of object, where each object is a data item. It can have as many numeric properties as needed. It also has a name property that identifies the data item.


Here is a minimal example of the data structure:

const data = [
   {var1: 5.1, var2: 3.5, ..., name: 'Mark'},
   {var1: 4.9, var2: 3.0, ..., name: 'Rosa'},
   ...
@@ -86,4 +86,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Spider / Radar inspiration

If you're looking for inspiration to create your next Spider / Radar, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Spider / Radar looks good!

visit

Radar chart with several groups

The process to get a radar chart with several groups is very similar to the previous example.

We just need to create a color scale and add a shape for each item of the dataset through a loop. Do not try to add too many groups on the same figure, it make it totally unreadable.

speedaccelerationconsosafetystyleprice

A radar chart with several groups displayed on the same figure. Made with React and d3.js

ToDospider chart with small multiple to make it more readable

Animation

It is common to have a radar chart that is updated when a button is clicked on the application. It is possible to implement a smooth, animated transition between states thanks to the react-spring library.

The following example illustrates this with a real world example. The radar chart is animated, together with a line chart and a lollipop.


GIF of a radar chart, a line chart and a lollipop that animate between dataset

Radar chart, line chart an lollipop with animated transition

Three charts connected to same buttons, with smooth, synchronized animation when a button is clicked

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Spider / Radar inspiration

If you're looking for inspiration to create your next Spider / Radar, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Spider / Radar looks good!

visit

Radar chart with several groups

The process to get a radar chart with several groups is very similar to the previous example.

We just need to create a color scale and add a shape for each item of the dataset through a loop. Do not try to add too many groups on the same figure, it make it totally unreadable.

speedaccelerationconsosafetystyleprice

A radar chart with several groups displayed on the same figure. Made with React and d3.js

ToDospider chart with small multiple to make it more readable

Animation

It is common to have a radar chart that is updated when a button is clicked on the application. It is possible to implement a smooth, animated transition between states thanks to the react-spring library.

The following example illustrates this with a real world example. The radar chart is animated, together with a line chart and a lollipop.


GIF of a radar chart, a line chart and a lollipop that animate between dataset

Radar chart, line chart an lollipop with animated transition

Three charts connected to same buttons, with smooth, synchronized animation when a button is clicked

Ranking

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/react-dataviz-animation-with-react-spring.html b/react-dataviz-animation-with-react-spring.html index 6bf723c4..395bfd14 100644 --- a/react-dataviz-animation-with-react-spring.html +++ b/react-dataviz-animation-with-react-spring.html @@ -1 +1 @@ -React-spring for data visualization

React-spring for data visualization


This post is dedicated to react-spring, a javascript library for spring animations. It quickly explains what it is and how it works, and then explains how it can be used in the field of data visualization.

A minimal react-spring dataviz example. A viz component expect a position and a color prop. But it smoothly animates the transition.

-What is a spring animation?

Spring animations are different than typical CSS easing animation. They're built on spring physics, which gives a more fluid and organic feel. The best way to be introduced to this concept is to read Josh Comeau's friendly Introduction to Spring Physics

To quote him directly:

Spring physics are like a secret ingredient; they make all animations taste better

-Most basic react spring example

The best tool to build a spring animation in the react world is react-spring, a library dedicated to it. If you're not familiar with it already you probably want to take a look at their home page.

Let's start with a basic example showing how to animate a very basic viz component that just renders a circle.

A very basic animation using react and react-spring.

The useSpring funtion can take 2 types of input: an object or a function

  • if object, it returns an object that has the values of our animation
  • if function, it returns an array of length 2. First item is the object mentionned above. item 2 is the api that controls the spring. api is used for imperative style

-Animating axes

A common hassle is to animate axes, since it's a lot of svg elements.

A very basic animation using react and react-spring.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +React-spring for data visualization

React-spring for data visualization


This post is dedicated to react-spring, a javascript library for spring animations. It quickly explains what it is and how it works, and then explains how it can be used in the field of data visualization.

A minimal react-spring dataviz example. A viz component expect a position and a color prop. But it smoothly animates the transition.

-What is a spring animation?

Spring animations are different than typical CSS easing animation. They're built on spring physics, which gives a more fluid and organic feel. The best way to be introduced to this concept is to read Josh Comeau's friendly Introduction to Spring Physics

To quote him directly:

Spring physics are like a secret ingredient; they make all animations taste better

-Most basic react spring example

The best tool to build a spring animation in the react world is react-spring, a library dedicated to it. If you're not familiar with it already you probably want to take a look at their home page.

Let's start with a basic example showing how to animate a very basic viz component that just renders a circle.

A very basic animation using react and react-spring.

The useSpring funtion can take 2 types of input: an object or a function

  • if object, it returns an object that has the values of our animation
  • if function, it returns an array of length 2. First item is the object mentionned above. item 2 is the api that controls the spring. api is used for imperative style

-Animating axes

A common hassle is to animate axes, since it's a lot of svg elements.

A very basic animation using react and react-spring.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/ridgeline.html b/ridgeline.html index 887c3475..bdaf3000 100644 --- a/ridgeline.html +++ b/ridgeline.html @@ -1,4 +1,4 @@ -Ridgeline chart with React

Ridgeline chart

Dataviz logo representing a Joyplot chart.

A ridgeline chart is a chart type that shows the distribution of a numeric variable for several groups, stacked one of top of each other. This page is a step-by-step guide on how to build your own histogram for the web, using React and D3.js.

It starts by describing how the data should be organized and how to initialize the ridgeline component. It then quickly recalls how to compute and draw a kernel density, and shows how to stack this information for several groups of a dataset. πŸ™‡β€β™‚οΈ.

Useful links

The Data

To build a ridgeline chart, the input dataset must provide a set ofnumeric values for several groups.

The best way to format this kind of information is with an array of object. Each object represents a group. Agroup property provides the group name, and a values property provides the values.


Here is a minimal example of the data structure:

export const data = [
+Ridgeline chart with React

Ridgeline chart

Dataviz logo representing a Joyplot chart.

A ridgeline chart is a chart type that shows the distribution of a numeric variable for several groups, stacked one of top of each other. This page is a step-by-step guide on how to build your own histogram for the web, using React and D3.js.

It starts by describing how the data should be organized and how to initialize the ridgeline component. It then quickly recalls how to compute and draw a kernel density, and shows how to stack this information for several groups of a dataset. πŸ™‡β€β™‚οΈ.

Useful links

The Data

To build a ridgeline chart, the input dataset must provide a set ofnumeric values for several groups.

The best way to format this kind of information is with an array of object. Each object represents a group. Agroup property provides the group name, and a values property provides the values.


Here is a minimal example of the data structure:

export const data = [
   {
     group: "A",
     values: [0, 0, 2, 2, 2, 0, 0, 1],
@@ -54,4 +54,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Ridgeline inspiration

If you're looking for inspiration to create your next Ridgeline, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Ridgeline looks good!

visit

Variations

Ridgeline charts are not the only way to compare the distribution of several groups in a dataset. Boxplots, violins, histograms and densities are variations that could interst you in order to solve this goal. Check the examples below to get the code.

Picture of a basic violin chart built in react

Basic violin plot

Learn how to build a basic violin chart with d3 and react

Picture of a density plot with multiple groups

Density plot with multiple groups

How to add several groups on the same density plot

Picture of a histogram with small multiple built with react and d3.js

Small multiple

Create one panel per group to show its distribution separately

Picture of a histogram with multiple groups built with react and d3.js

Multiple groups

A histogram with <b>multiple</b> groups displayed on the same axis.

Picture of a boxplot with jitter built using react and d3.js

Boxplot with jitter

Add individual data points using jitter on top of the boxplot

Picture of a basic boxplot built with react and d3

Basic boxplot

How to build a basic boxplot with react

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Ridgeline inspiration

If you're looking for inspiration to create your next Ridgeline, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Ridgeline looks good!

visit

Variations

Ridgeline charts are not the only way to compare the distribution of several groups in a dataset. Boxplots, violins, histograms and densities are variations that could interst you in order to solve this goal. Check the examples below to get the code.

Picture of a basic violin chart built in react

Basic violin plot

Learn how to build a basic violin chart with d3 and react

Picture of a density plot with multiple groups

Density plot with multiple groups

How to add several groups on the same density plot

Picture of a histogram with small multiple built with react and d3.js

Small multiple

Create one panel per group to show its distribution separately

Picture of a histogram with multiple groups built with react and d3.js

Multiple groups

A histogram with <b>multiple</b> groups displayed on the same axis.

Picture of a boxplot with jitter built using react and d3.js

Boxplot with jitter

Add individual data points using jitter on top of the boxplot

Picture of a basic boxplot built with react and d3

Basic boxplot

How to build a basic boxplot with react

Distribution

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/sankey-diagram.html b/sankey-diagram.html index 141d63e0..efa0e04e 100644 --- a/sankey-diagram.html +++ b/sankey-diagram.html @@ -1,4 +1,4 @@ -How to build a Sankey Diagram with React and D3.

Sankey Diagram

Dataviz logo representing a Sankey chart.

A Sankey Diagram display flows. Several entities (nodes) are represented by rectangles or text. Directed links are represented with arrows or arcs that have a width proportional to the importance of the flow.

This tutorial explains how to use React, D3.js and the d3-sankey plugin to build a Sankey diagram. It comes with explanations and code sandboxes to play along with the suggested implementation.

Useful links

The Data

Two layers of information are required to build a Sankey diagram: a list of nodes to build the rectangles and a list of links to build the paths between them.

Many different data structures can be used to store such information. In this tutorial I suggest to start with the following:

const data = {
+How to build a Sankey Diagram with React and D3.

Sankey Diagram

Dataviz logo representing a Sankey chart.

A Sankey Diagram display flows. Several entities (nodes) are represented by rectangles or text. Directed links are represented with arrows or arcs that have a width proportional to the importance of the flow.

This tutorial explains how to use React, D3.js and the d3-sankey plugin to build a Sankey diagram. It comes with explanations and code sandboxes to play along with the suggested implementation.

Useful links

The Data

Two layers of information are required to build a Sankey diagram: a list of nodes to build the rectangles and a list of links to build the paths between them.

Many different data structures can be used to store such information. In this tutorial I suggest to start with the following:

const data = {
   nodes: [
       { node: 0, name: "node0" },
       { node: 1, name: "node1" },
@@ -79,4 +79,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Sankey inspiration

If you're looking for inspiration to create your next Sankey, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Sankey looks good!

visit

Application to a real dataset

This Sankey diagram visualizes the flow of energy: supplies are on the left, and demands are on the right. It is a reproduction of this famous observable example. Links show how varying amounts of energy are converted or transmitted before being consumed or lost.

The code is very similar to the example above. On top of it, a color scale is used for the node and connection colors, and some text labels have been added.

A Sankey diagram showing the flow of energy. Supplies on the left, demands on the right.

ToDoAdd hover effect to highlight links
ToDoAdd gradient along links
ToDoFix types

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Sankey inspiration

If you're looking for inspiration to create your next Sankey, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Sankey looks good!

visit

Application to a real dataset

This Sankey diagram visualizes the flow of energy: supplies are on the left, and demands are on the right. It is a reproduction of this famous observable example. Links show how varying amounts of energy are converted or transmitted before being consumed or lost.

The code is very similar to the example above. On top of it, a color scale is used for the node and connection colors, and some text labels have been added.

A Sankey diagram showing the flow of energy. Supplies on the left, demands on the right.

ToDoAdd hover effect to highlight links
ToDoAdd gradient along links
ToDoFix types

Flow

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/scatter-plot.html b/scatter-plot.html index 4ff7f412..b46c7d08 100644 --- a/scatter-plot.html +++ b/scatter-plot.html @@ -1,4 +1,4 @@ -How to build a scatter plot with React and D3.

Scatterplot

Dataviz logo representing a ScatterPlot chart.

A scatterplot displays the relationship between 2 numeric variables. This page is a step-by-step guide on how to build your own scatterplot for the web, using React and D3.js.

It starts with very basic concepts like data structure, scales and svg circle rendering. It then shows how to add interactivity to the chart with hover effects and tooltips. At the end of the post, you should be able to build you own ready-to-publish scatterplot πŸ™‡β€β™‚οΈ.

Useful links

The Data

The dataset used to build a scatterplot is usually an array of objects.

For each object, at least 2 properties are required: x and y. The value of x will control the position of the datapoint on the horizontal axis. The value of y will be linked with the vertical axis.

const data = [
+How to build a scatter plot with React and D3.

Scatterplot

Dataviz logo representing a ScatterPlot chart.

A scatterplot displays the relationship between 2 numeric variables. This page is a step-by-step guide on how to build your own scatterplot for the web, using React and D3.js.

It starts with very basic concepts like data structure, scales and svg circle rendering. It then shows how to add interactivity to the chart with hover effects and tooltips. At the end of the post, you should be able to build you own ready-to-publish scatterplot πŸ™‡β€β™‚οΈ.

Useful links

The Data

The dataset used to build a scatterplot is usually an array of objects.

For each object, at least 2 properties are required: x and y. The value of x will control the position of the datapoint on the horizontal axis. The value of y will be linked with the vertical axis.

const data = [
   {
     x: 2,
     y: 4
@@ -229,4 +229,4 @@
       onMouseLeave={() => setHoveredGroup(null)} // and to set it back to null
     />
   );
-});

Last but not least, some css needs to be added to customize the circle depending on if they are in default, .dimmed or :hover mode.

Note that the filter: saturate(0) is a good way to dim unwanted circles. Also, playing with transition-delay and transition-duration adds to animate the transition is a nice touch you should consider. Check the code below the example to see the full css.

The hover effect is another big topic in data visualization. A dedicated post will be published soon on the topic, feel free to subscribe to know when.

Scatterplot inspiration

If you're looking for inspiration to create your next Scatterplot, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Scatterplot looks good!

visit

Real-life application

Let's apply the concepts learned above to a real-life example.

I like this scatterplot originally published on the data wrapper blog. It shows a strong correlation between vulnerability to climate change and CO2 emissions.


The chart has several features that are interesting to reproduce fom a technical point of view:

  • Custom annotation: only a fraction of the country names are written
  • Hover effect: the hovered country is highlighted with a black stroke. After a short delay, countries of other groups are dimmed. Note that the effect is triggered once the mouse approaches the marker, no need to be perfectly on top.
  • Tooltip: highly customized and linked to the mouse position

The countries with the highest vulnerability to climate change have the lowest CO2 emissions

All countries sorted by their vulnerability and readiness to climate change. The size shows the CO2 emission per person in that country.

High Readiness↑Low Readiness↓QatarBahrainU.S.Trinidad and TobagoCzech RepublicSingaporeNorwayIndiaSudanChadSomalia

Reproduction of a chart originally published by Data Wrapper using react and d3.js.

Variations

The scatterplot examples described above are just the beginning of your journey. There is an infinite world of customization that is open to you. You can also explore related chart types that can be a good fit for your data:

Click on the overview below to get details and code.


gif of a scatterplot with voronoi diagram for closest point detection

Closest point detection with Voronoi

Using a voronoi diagram in the scatterplot background is a smart way to efficiently find the mouse closest point

a scatterplot made with react and rendered in canvas

Scatterplot in Canvas

Learn how to render a scatterplot in canvas to improve performances

Picture of a correlogram built with react and d3

Basic correlogram

Learn how to build a correlogram with react and d3

Picture of a simple bubble plot with a legend made with react and d3.js

Bubble plot

Learn how to build a bubble plot with react and d3.js

Picture of a hexbin chart made with React and d3.js

Hexbin chart

A hexbin chart split the figure in hexagons to show a 2d density

Picture of a timeseries chart made with React and D3.js: scatterplot and line chart in use.

Timeseries with moving average

A scatterplot used for timeseries, with the moving average shown as a line chart on top.

Useful links

The following links have been useful to create this page:

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +});

Last but not least, some css needs to be added to customize the circle depending on if they are in default, .dimmed or :hover mode.

Note that the filter: saturate(0) is a good way to dim unwanted circles. Also, playing with transition-delay and transition-duration adds to animate the transition is a nice touch you should consider. Check the code below the example to see the full css.

The hover effect is another big topic in data visualization. A dedicated post will be published soon on the topic, feel free to subscribe to know when.

Scatterplot inspiration

If you're looking for inspiration to create your next Scatterplot, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Scatterplot looks good!

visit

Real-life application

Let's apply the concepts learned above to a real-life example.

I like this scatterplot originally published on the data wrapper blog. It shows a strong correlation between vulnerability to climate change and CO2 emissions.


The chart has several features that are interesting to reproduce fom a technical point of view:

  • Custom annotation: only a fraction of the country names are written
  • Hover effect: the hovered country is highlighted with a black stroke. After a short delay, countries of other groups are dimmed. Note that the effect is triggered once the mouse approaches the marker, no need to be perfectly on top.
  • Tooltip: highly customized and linked to the mouse position

The countries with the highest vulnerability to climate change have the lowest CO2 emissions

All countries sorted by their vulnerability and readiness to climate change. The size shows the CO2 emission per person in that country.

High Readiness↑Low Readiness↓QatarBahrainU.S.Trinidad and TobagoCzech RepublicSingaporeNorwayIndiaSudanChadSomalia

Reproduction of a chart originally published by Data Wrapper using react and d3.js.

Variations

The scatterplot examples described above are just the beginning of your journey. There is an infinite world of customization that is open to you. You can also explore related chart types that can be a good fit for your data:

Click on the overview below to get details and code.


gif of a scatterplot with voronoi diagram for closest point detection

Closest point detection with Voronoi

Using a voronoi diagram in the scatterplot background is a smart way to efficiently find the mouse closest point

a scatterplot made with react and rendered in canvas

Scatterplot in Canvas

Learn how to render a scatterplot in canvas to improve performances

Picture of a correlogram built with react and d3

Basic correlogram

Learn how to build a correlogram with react and d3

Picture of a simple bubble plot with a legend made with react and d3.js

Bubble plot

Learn how to build a bubble plot with react and d3.js

Picture of a hexbin chart made with React and d3.js

Hexbin chart

A hexbin chart split the figure in hexagons to show a 2d density

Picture of a timeseries chart made with React and D3.js: scatterplot and line chart in use.

Timeseries with moving average

A scatterplot used for timeseries, with the moving average shown as a line chart on top.

Useful links

The following links have been useful to create this page:

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/shape-morphism-for-dataviz-with-react.html b/shape-morphism-for-dataviz-with-react.html index cbe4979a..32709891 100644 --- a/shape-morphism-for-dataviz-with-react.html +++ b/shape-morphism-for-dataviz-with-react.html @@ -1,3 +1,3 @@ -Shape morphism for data visualization

Shape morphism for data visualization


Shape morphism is the art of transitioning between 2 shapes as smoothly as possible. This post explores how it can be useful for data visualization and how it can be done using React, d3.js, react-spring and flubber.

This post is about shape morphism, which means animating the properties that define the actual shape of the elements.
As always when talking about animation, it is good to recall this citation by Josh Comeau:

Animation is like salt: too much of it spoils the dish

-Shape morphism for dataviz: some examples

Here is a list of nifty viz examples using shape morphism to transition between several viz types


-Shape morphism: why

In the field of data visualization shape morphism is mostly usefull to transition between 2 chart types. It is pretty hard to implement that kind of smooth transition so why should we even care?


  • Eye catching effect

  • Highlight the direct relationship between 2 charts. During the transition one can follow a specific item and understand it's the same.
  • Make sure that we're looking at the same dataset, but represented differently

-What are we trying to do

Sometimes in dataviz we want to transition between 2 chart types, let's say between a pie chart and a barplot. This is pretty hard since the shapes used for those 2 charts are very different: arc versus rectangle.


This is still possible thanks to a few libraries. This post suggests to use d3.js to build the start and end svg path, flubberto interpolate those path, react-spring for the animation and react for the rendering.


This is the kind of thing we're gonna learn to build:


-Shape morphism on the web: a review

I knew nothing about shape morphism 3 weeks ago. It took me a lot of effort to browse the web and find what the most appropriate tools are. To avoid you the hassle, here is a quick summary:


  • SMIL (Synchronized Multimedia Integration Language) is a feature introduced in firefox 4, allowing to follow a motion path. Basically it means you can use an animate element in your svg that will support shape morphism.
    Unfortunately, this feature is probably get deprecated soon. Furthermore, it supports transition only between shapes with the same number of nodes.
    DocCodePen.

  • pure CSS: Chrome has started to allow shape morphing through css. You can simply change the d attribute of a path in a css file and add sometransition to it. But chrome only and same number of nodes only.
    CodePen

  • greenSock MorphSvg plugin: a promising javascript library for shape morphism, widely cited on the internet. Supports shapes with different number of nodes. But it's not free and not open source.
    WebsiteCodePen

  • superformula is a mathematic formula that can be used to describe many complex shapes. Using 6 numbers as parameters, this formula can build many complex shapes. Interpolating between 2 shapes becomes easy: we just have to interpolate those numbers. Problem: it does not work with any shape and building a chart from this formula is thus impossible.
    Example

  • d3-interpolate is a d3 module that provides a variety of interpolation methods. It works for paths, even with different number of nodes. But when the shape 2 has more nodes than shape 1 it just adds some nodes to the end of the shape 1 path. This result in a bad visual effect.
    Doc

  • d3-interpolate-path is an open-source js library that adds an interpolator optimized for SVG path elements. It works very well for path including segments only, but from my experience less well for arcs.
    DocDemo

  • Vizzu is a library for animated data visualizations and data stories. It looks very promising for transition between chart types. But since it is a library, it means that customization is limited to the offered options.
    DocDemo

None of the item of this list suits my need. We need an open source library capable of interpolating any path, even with different number of nodes..

-Shape interpolation with flubber

flubber is an open source javascript library built by Noah Veltman. Unlike most of the shape morphism libraries it works very well to interpolate shapes that are completely different and don't have the same number of nodes.


Let's start by creating 2 svg shapes

const shape1 = "M10,140 L50,60 L90,140 Z"; // triangle
+Shape morphism for data visualization

Shape morphism for data visualization


Shape morphism is the art of transitioning between 2 shapes as smoothly as possible. This post explores how it can be useful for data visualization and how it can be done using React, d3.js, react-spring and flubber.

This post is about shape morphism, which means animating the properties that define the actual shape of the elements.
As always when talking about animation, it is good to recall this citation by Josh Comeau:

Animation is like salt: too much of it spoils the dish

-Shape morphism for dataviz: some examples

Here is a list of nifty viz examples using shape morphism to transition between several viz types


-Shape morphism: why

In the field of data visualization shape morphism is mostly usefull to transition between 2 chart types. It is pretty hard to implement that kind of smooth transition so why should we even care?


  • Eye catching effect

  • Highlight the direct relationship between 2 charts. During the transition one can follow a specific item and understand it's the same.
  • Make sure that we're looking at the same dataset, but represented differently

-What are we trying to do

Sometimes in dataviz we want to transition between 2 chart types, let's say between a pie chart and a barplot. This is pretty hard since the shapes used for those 2 charts are very different: arc versus rectangle.


This is still possible thanks to a few libraries. This post suggests to use d3.js to build the start and end svg path, flubberto interpolate those path, react-spring for the animation and react for the rendering.


This is the kind of thing we're gonna learn to build:


-Shape morphism on the web: a review

I knew nothing about shape morphism 3 weeks ago. It took me a lot of effort to browse the web and find what the most appropriate tools are. To avoid you the hassle, here is a quick summary:


  • SMIL (Synchronized Multimedia Integration Language) is a feature introduced in firefox 4, allowing to follow a motion path. Basically it means you can use an animate element in your svg that will support shape morphism.
    Unfortunately, this feature is probably get deprecated soon. Furthermore, it supports transition only between shapes with the same number of nodes.
    DocCodePen.

  • pure CSS: Chrome has started to allow shape morphing through css. You can simply change the d attribute of a path in a css file and add sometransition to it. But chrome only and same number of nodes only.
    CodePen

  • greenSock MorphSvg plugin: a promising javascript library for shape morphism, widely cited on the internet. Supports shapes with different number of nodes. But it's not free and not open source.
    WebsiteCodePen

  • superformula is a mathematic formula that can be used to describe many complex shapes. Using 6 numbers as parameters, this formula can build many complex shapes. Interpolating between 2 shapes becomes easy: we just have to interpolate those numbers. Problem: it does not work with any shape and building a chart from this formula is thus impossible.
    Example

  • d3-interpolate is a d3 module that provides a variety of interpolation methods. It works for paths, even with different number of nodes. But when the shape 2 has more nodes than shape 1 it just adds some nodes to the end of the shape 1 path. This result in a bad visual effect.
    Doc

  • d3-interpolate-path is an open-source js library that adds an interpolator optimized for SVG path elements. It works very well for path including segments only, but from my experience less well for arcs.
    DocDemo

  • Vizzu is a library for animated data visualizations and data stories. It looks very promising for transition between chart types. But since it is a library, it means that customization is limited to the offered options.
    DocDemo

None of the item of this list suits my need. We need an open source library capable of interpolating any path, even with different number of nodes..

-Shape interpolation with flubber

flubber is an open source javascript library built by Noah Veltman. Unlike most of the shape morphism libraries it works very well to interpolate shapes that are completely different and don't have the same number of nodes.


Let's start by creating 2 svg shapes

const shape1 = "M10,140 L50,60 L90,140 Z"; // triangle
 const shape2 = "M350,50 L400,83 L400,116 L350,150 L300,116 L300,83"; // polygon

It's very straightforward to interpolate a y between the 2 of them thanks to the interpolate() function offlubber. This function expects 2 arguments: the starting shape and the ending shape:

const interpolator = interpolate(shape1, shape2);

interpolate() returns a function. This function accepts only 1 argument: a value between 0 (start) and 1 (end). It will return the interpolated shape for this progress.

interpolator(0.2)
-// M110,58L113.25,62.825L116.5,67.65L119.75,72.475L123,77.3L126.25,82.125L129.5,86.95L.......Z

Here is a visualization of the final result

step: 0.0

Switching from a triangle to a polygon using flubber for shape interpolation


Awesome video by the Flubber creator: link

-Animating the transition with react-spring

Now that we know how to build an interpolated shape between a starting and an ending point, let's animated this transition using react-spring.

The transition is now animated thanks to react-spring, a react library for spring animation.

-Pie chart to barplot transtion

I knew nothing about shape morphism 3 weeks ago. It took me a lot of effort to browse the web and find what the most appropriate tools are. To avoid you the hassle, here is a quick summary:

-Violin to boxplot transition

I knew nothing about shape morphism 3 weeks ago. It took me a lot of effort to browse the web and find what the most appropriate tools are. To avoid you the hassle, here is a quick summary:

How to smoothly transition between a boxplot and a violin plot. Math by d3.js, rendering using react, animation using react-spring and interpolation using flubber.


Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +// M110,58L113.25,62.825L116.5,67.65L119.75,72.475L123,77.3L126.25,82.125L129.5,86.95L.......Z

Here is a visualization of the final result

step: 0.0

Switching from a triangle to a polygon using flubber for shape interpolation


Awesome video by the Flubber creator: link

-Animating the transition with react-spring

Now that we know how to build an interpolated shape between a starting and an ending point, let's animated this transition using react-spring.

The transition is now animated thanks to react-spring, a react library for spring animation.

-Pie chart to barplot transtion

I knew nothing about shape morphism 3 weeks ago. It took me a lot of effort to browse the web and find what the most appropriate tools are. To avoid you the hassle, here is a quick summary:

-Violin to boxplot transition

I knew nothing about shape morphism 3 weeks ago. It took me a lot of effort to browse the web and find what the most appropriate tools are. To avoid you the hassle, here is a quick summary:

How to smoothly transition between a boxplot and a violin plot. Math by d3.js, rendering using react, animation using react-spring and interpolation using flubber.


Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml index 1e0de62e..f604c91f 100644 --- a/sitemap.xml +++ b/sitemap.xml @@ -1,77 +1,77 @@ -https://www.react-graph-gallery.com2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/2d-density-plot2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/about2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/add-hover-interaction-to-graph2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/all2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/animation2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/arc-diagram2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/area-plot2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/articles2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/barplot2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/boxplot2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/bubble-map2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/bubble-plot2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/build-axis-with-react2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/cartogram2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/chord-diagram2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/choropleth-map2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/circular-barplot2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/circular-packing2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/connected-scatter-plot2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/connection-map2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/correlogram2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/cross-graph-highlight-interaction2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/dataset-transition2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/dendrogram2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/density-plot2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/donut2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/arc-diagram-vertical2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/barplot-data-transition-animation2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/barplot-stacked-horizontal2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/barplot-stacked-vertical2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/boxplot-horizontal2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/boxplot-jitter2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/circle-packing-with-d3-force2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/histogram-mirror2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/histogram-small-multiple2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/histogram-with-several-groups2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/line-chart-synchronized-cursors2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/network-diagram-with-colored-groups2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/radar-chart-animation2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/scatterplot-basic-canvas2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/scatterplot-tooltip-with-voronoi-for-closest-point-detection2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/example/timeseries-moving-average2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/fix-canvas-blurry-dataviz2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/heatmap2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/hexbin-map2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/hierarchical-edge-bundling2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/histogram2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/interactivity2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/line-chart2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/lollipop-plot2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/make-a-graph-responsive2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/map2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/network-chart2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/parallel-plot2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/pie-plot2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/radar-chart2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/react-dataviz-animation-with-react-spring2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/ridgeline2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/sankey-diagram2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/scatter-plot2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/shape-morphism-for-dataviz-with-react2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/stacked-area-plot2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/stacked-barplot-with-negative-values2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/streamchart2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/subscribe2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/timeseries2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/treemap2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/typescript-d3-axis2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/violin-plot2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/viz-from-the-future2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/voronoi2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/what-is-a-color2024-04-02T09:22:31.003Zdaily0.7 -https://www.react-graph-gallery.com/wordcloud2024-04-02T09:22:31.003Zdaily0.7 +https://www.react-graph-gallery.com2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/2d-density-plot2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/about2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/add-hover-interaction-to-graph2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/all2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/animation2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/arc-diagram2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/area-plot2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/articles2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/barplot2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/boxplot2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/bubble-map2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/bubble-plot2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/build-axis-with-react2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/cartogram2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/chord-diagram2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/choropleth-map2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/circular-barplot2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/circular-packing2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/connected-scatter-plot2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/connection-map2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/correlogram2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/cross-graph-highlight-interaction2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/dataset-transition2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/dendrogram2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/density-plot2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/donut2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/arc-diagram-vertical2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/barplot-data-transition-animation2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/barplot-stacked-horizontal2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/barplot-stacked-vertical2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/boxplot-horizontal2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/boxplot-jitter2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/circle-packing-with-d3-force2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/histogram-mirror2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/histogram-small-multiple2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/histogram-with-several-groups2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/line-chart-synchronized-cursors2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/network-diagram-with-colored-groups2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/radar-chart-animation2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/scatterplot-basic-canvas2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/scatterplot-tooltip-with-voronoi-for-closest-point-detection2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/example/timeseries-moving-average2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/fix-canvas-blurry-dataviz2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/heatmap2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/hexbin-map2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/hierarchical-edge-bundling2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/histogram2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/interactivity2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/line-chart2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/lollipop-plot2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/make-a-graph-responsive2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/map2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/network-chart2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/parallel-plot2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/pie-plot2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/radar-chart2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/react-dataviz-animation-with-react-spring2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/ridgeline2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/sankey-diagram2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/scatter-plot2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/shape-morphism-for-dataviz-with-react2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/stacked-area-plot2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/stacked-barplot-with-negative-values2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/streamchart2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/subscribe2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/timeseries2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/treemap2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/typescript-d3-axis2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/violin-plot2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/viz-from-the-future2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/voronoi2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/what-is-a-color2024-04-02T09:26:22.300Zdaily0.7 +https://www.react-graph-gallery.com/wordcloud2024-04-02T09:26:22.300Zdaily0.7 \ No newline at end of file diff --git a/stacked-area-plot.html b/stacked-area-plot.html index a5fb0b68..78f79a37 100644 --- a/stacked-area-plot.html +++ b/stacked-area-plot.html @@ -1,4 +1,4 @@ -Stacked Area charts with React

Stacked Area charts

Dataviz logo representing a StackedArea chart.

A stacked area chart is an evolution of an area chart used to display the evolution of several groups in a dataset. This section explains how to build it with d3.js and react. It focus on stacking, so make sure to read the area chart section first.

Useful links

The Data

Most of the time the input dataset is an array where each item is an object.
Each object provides information for a step on the X axis. It has a value like x that provides the exact position on the X axis. It then has several numeric values, one for each group of the dataset.


Here is a minimal example:

const data = [
+Stacked Area charts with React

Stacked Area charts

Dataviz logo representing a StackedArea chart.

A stacked area chart is an evolution of an area chart used to display the evolution of several groups in a dataset. This section explains how to build it with d3.js and react. It focus on stacking, so make sure to read the area chart section first.

Useful links

The Data

Most of the time the input dataset is an array where each item is an object.
Each object provides information for a step on the X axis. It has a value like x that provides the exact position on the X axis. It then has several numeric values, one for each group of the dataset.


Here is a minimal example:

const data = [
   {
     x: 1,
     groupA: 38,
@@ -108,4 +108,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Stacked Area inspiration

If you're looking for inspiration to create your next Stacked Area, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Stacked Area looks good!

visit

Offset and Curve types

Stacked area charts can easily be customized to use other offset and smoothing algorithm. This process can be used to create streamgraphs which are a varation of the stacked area graph.

The offset type controls how the data are stacked. You can read about the offset options available in the official documentation or play with the little example below.

The curve type controls how the smoothing of each shape is made. There are a myriad of options described in the official documentation.

Offset typeCurve type
246810

Try d3.js various options to offset the data and smooth shapes. See a smooth transition between options.

The animation uses react-spring to run. I'll publish a full blogpost on the topic soon!

Get notified


Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Stacked Area inspiration

If you're looking for inspiration to create your next Stacked Area, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Stacked Area looks good!

visit

Offset and Curve types

Stacked area charts can easily be customized to use other offset and smoothing algorithm. This process can be used to create streamgraphs which are a varation of the stacked area graph.

The offset type controls how the data are stacked. You can read about the offset options available in the official documentation or play with the little example below.

The curve type controls how the smoothing of each shape is made. There are a myriad of options described in the official documentation.

Offset typeCurve type
246810

Try d3.js various options to offset the data and smooth shapes. See a smooth transition between options.

The animation uses react-spring to run. I'll publish a full blogpost on the topic soon!

Get notified


Evolution

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/stacked-barplot-with-negative-values.html b/stacked-barplot-with-negative-values.html index 6afc5df0..27c3fea8 100644 --- a/stacked-barplot-with-negative-values.html +++ b/stacked-barplot-with-negative-values.html @@ -1 +1 @@ -Dealing with negative values on a stacked barplot

Dealing with negative values on a stacked barplot


Drawing a stacked barplot sounds like pretty basic task for somebody into dataviz. But it gets surprisingly tricky once the dataset includes negative values.

This post explains how to deal with it, suggesting several options coming together with some reproducible code examples.

πŸ” Regular stacked barplot with positive values

Let's consider a company that has 3 employees: a, b and c. Each month those employees sell umbrellas and make money.

In January, they made 1, 1 and 2 dollars respectively. It's pretty easy to represent those sales as a stacked barplot!

There is even a bonus! The total height of those bars is 4. So is the value of the stack on the Y axis. We now know what's the total revenue of the company πŸŽ‰!

Stacking positive values is straightforward


Now let's follow the same process for the 12 months of the year. That makes a stacked area barplot built with react and d3.js. If you need explanations for the code, please refer to the d3.js gallery or to the barplot section of the react gallery.


A stacked area chart with positive values only. Built with react and d3.js


That's the end of the easy part. Now, let's say that sometimes employees spend more money than what they make.

We now have some negative values in the dataset 😳. How can we deal with it?

1️⃣ Stacked barplot with negative values: the diverging strategy

We are in January but this time, employee A lost 1$! πŸ˜₯

To represent this on the stack, we can add all the positive values on top of the chart, and all the negative ones below the 0 axis.

It is still very easy to see how much each employee made in a glimpse!

However, it is now impossible to know what's the company revenue! Indeed, the total height of the bars is 4, the value on the y axis is 3, but the real revenue is 1 + 2 - 1 = 2!

shema of a stacked barplot with the diverging strategy for stacking

Stacking with negative values with all negative values below the 0 axis


Using almost the same code we can build the stacked barplot including those negative values. Note that when stacking the data with the stack() function of d3, the specific stackOffsetDiverging offset parameter must be passed, handling all the work for us (doc).


With the diverging strategy, all negative values are located under the 0 baseline.


Let's recap the pros and cons of this diverging option:

Pros

  • Easy to read the value of each item
  • Obvious what's negative and what's positive

Cons

  • Impossible to know the total value of each stack
  • A series can jump from the bottom to the top of the chart and is thus hard to follow

2️⃣ Stacked barplot with negative values: the overlapping strategy

Another strategy can be applied to stack the items including negative values.

Items can be added one by one, with rectangles going up when values are positive and going down when values are negative.

Stacking items by overlapping the items on top of each other.


It's important to understand that here, the item order is important. We will get very different results depending on the order since not all groups are visible.


With the overlapping strategy items are drawn successively, going up and down and overlapping if necessary


Let's recap the pros and cons of this diverging option:

Pros

  • Depending on the group order, the Y value can reflect the sum of the items. But it's not guarantee.

Cons

  • Groups overlap each other. Information is hidden. Chart is unreadable

Conclusion

In my opinion the first option (diverging) makes much more sense than the second one (overlapping). The cons are very limited:

  • It is true that the net total value is not available. But if that's what interests you, you don't have to split the dataset by subgroups, just create a line chart with a single line!
  • Having a group flipping from top to bottom is indeed annoying. However, the hover effect that is included allows to quickly see what happens for a specific group.

It's also important to note that most dataviz tools choosed this approach. Here is an example using the same dataset using the ggplot2library (left) and data wrapper (right).


stacked barplot with R and ggplot2stacked barplot with data wrapper

Same dataset that includes negative values plotted with ggplot2 (left) and data wrapper (right)


Last but not least, I really like this example by chartio that fixes the non available total issue by adding a line on top of the stacked barchart to show the total:


stacked barplot with chartio

Chartio displays the total of each timestamp using a line chart on top of the stacked items.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +Dealing with negative values on a stacked barplot

Dealing with negative values on a stacked barplot


Drawing a stacked barplot sounds like pretty basic task for somebody into dataviz. But it gets surprisingly tricky once the dataset includes negative values.

This post explains how to deal with it, suggesting several options coming together with some reproducible code examples.

πŸ” Regular stacked barplot with positive values

Let's consider a company that has 3 employees: a, b and c. Each month those employees sell umbrellas and make money.

In January, they made 1, 1 and 2 dollars respectively. It's pretty easy to represent those sales as a stacked barplot!

There is even a bonus! The total height of those bars is 4. So is the value of the stack on the Y axis. We now know what's the total revenue of the company πŸŽ‰!

Stacking positive values is straightforward


Now let's follow the same process for the 12 months of the year. That makes a stacked area barplot built with react and d3.js. If you need explanations for the code, please refer to the d3.js gallery or to the barplot section of the react gallery.


A stacked area chart with positive values only. Built with react and d3.js


That's the end of the easy part. Now, let's say that sometimes employees spend more money than what they make.

We now have some negative values in the dataset 😳. How can we deal with it?

1️⃣ Stacked barplot with negative values: the diverging strategy

We are in January but this time, employee A lost 1$! πŸ˜₯

To represent this on the stack, we can add all the positive values on top of the chart, and all the negative ones below the 0 axis.

It is still very easy to see how much each employee made in a glimpse!

However, it is now impossible to know what's the company revenue! Indeed, the total height of the bars is 4, the value on the y axis is 3, but the real revenue is 1 + 2 - 1 = 2!

shema of a stacked barplot with the diverging strategy for stacking

Stacking with negative values with all negative values below the 0 axis


Using almost the same code we can build the stacked barplot including those negative values. Note that when stacking the data with the stack() function of d3, the specific stackOffsetDiverging offset parameter must be passed, handling all the work for us (doc).


With the diverging strategy, all negative values are located under the 0 baseline.


Let's recap the pros and cons of this diverging option:

Pros

  • Easy to read the value of each item
  • Obvious what's negative and what's positive

Cons

  • Impossible to know the total value of each stack
  • A series can jump from the bottom to the top of the chart and is thus hard to follow

2️⃣ Stacked barplot with negative values: the overlapping strategy

Another strategy can be applied to stack the items including negative values.

Items can be added one by one, with rectangles going up when values are positive and going down when values are negative.

Stacking items by overlapping the items on top of each other.


It's important to understand that here, the item order is important. We will get very different results depending on the order since not all groups are visible.


With the overlapping strategy items are drawn successively, going up and down and overlapping if necessary


Let's recap the pros and cons of this diverging option:

Pros

  • Depending on the group order, the Y value can reflect the sum of the items. But it's not guarantee.

Cons

  • Groups overlap each other. Information is hidden. Chart is unreadable

Conclusion

In my opinion the first option (diverging) makes much more sense than the second one (overlapping). The cons are very limited:

  • It is true that the net total value is not available. But if that's what interests you, you don't have to split the dataset by subgroups, just create a line chart with a single line!
  • Having a group flipping from top to bottom is indeed annoying. However, the hover effect that is included allows to quickly see what happens for a specific group.

It's also important to note that most dataviz tools choosed this approach. Here is an example using the same dataset using the ggplot2library (left) and data wrapper (right).


stacked barplot with R and ggplot2stacked barplot with data wrapper

Same dataset that includes negative values plotted with ggplot2 (left) and data wrapper (right)


Last but not least, I really like this example by chartio that fixes the non available total issue by adding a line on top of the stacked barchart to show the total:


stacked barplot with chartio

Chartio displays the total of each timestamp using a line chart on top of the stacked items.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/streamchart.html b/streamchart.html index 8f5b3947..c0c67d5f 100644 --- a/streamchart.html +++ b/streamchart.html @@ -1,4 +1,4 @@ -Streamchart with React

Streamchart

Dataviz logo representing a Stream chart.

A streamgraph is a variation of the more common stacked area chart. It rounds edges and displays areas around the central axis which gives a nice impression of flow.

This section explains how to stack and smooth the data with d3.js, and render the shapes with react. It starts from the basic and goes until necessary customization like tooltips, hover effect, legend and annotation. Examples always come with editable sandboxes.

Useful links

The Data

Most of the time the input dataset is an array where each item is an object.

Each object provides information for a step on the X axis. It has a value like x or date that provides the exact position on the X axis. Then it has several numeric values, one for each group of the dataset.

Here is a minimal example:

const data = [
+Streamchart with React

Streamchart

Dataviz logo representing a Stream chart.

A streamgraph is a variation of the more common stacked area chart. It rounds edges and displays areas around the central axis which gives a nice impression of flow.

This section explains how to stack and smooth the data with d3.js, and render the shapes with react. It starts from the basic and goes until necessary customization like tooltips, hover effect, legend and annotation. Examples always come with editable sandboxes.

Useful links

The Data

Most of the time the input dataset is an array where each item is an object.

Each object provides information for a step on the X axis. It has a value like x or date that provides the exact position on the X axis. Then it has several numeric values, one for each group of the dataset.

Here is a minimal example:

const data = [
   {
     x: 1,
     groupA: 38,
@@ -97,4 +97,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Hover effect

It is pretty hard to follow the evolution of a specific group on a streamgraph.

It is common to add an hover effect to the figure: hovering over a group will highlight it, making it easier to follow its evolution. Try it on the graph below:

246810

StreamGraph with hover effect that highlights a specific series

There are various strategies to implement such an hover effect.

Here, I suggest to do everything in css using pseudo classes, and targetting svg elements only. Basically, everything in the svg container will be dimmed (lower opacity and saturation) when the mouse goes over the chart. But the specific shape that is hovered over will keep its full opacity thanks to a more specific css selector.

Hover effect is a big topic and I will post more about it soon!

Know when

Streamgraph inspiration

If you're looking for inspiration to create your next Streamgraph, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Streamgraph looks good!

visit

Streamgraph algorithm with transition

Our streamgraph is renderer using a set of path. The d attribute of those paths provides the boundary coordinates of those paths.

When a prop of the StreamGraph component updates, we might want to update the paths to represent the latest state of our application. It can be an update of the dataset, or an update of the function used to stack the data or smooth the area as below.

It is possible to smoothly animate this transition thanks to react-spring.

Offset typeCurve type
246810

Try d3.js various options to offset the data and smooth shapes. See a smooth transition between options.

The animation suggested above is a bit tricky to implement. Indeed, we need to transition from paths that do not have the same number of edges. It is possible thanks to a library called flubber but definitely deserves its own blogpost.

I'll publish a full blogpost on the topic soon!

Get notified
ToDofind why flubber does some weird interpolation in some cases

Application

The following chart is a real-life application of a streamgraph. It shows the evolution if the number of page-views for 5 tech websites in the last 7 years. My goal was to assess if the rise of chat-GPT had an impact on it.

This interactive chart has several interesting features:

  • slider: you can control the displayed time-frame thanks to a slider.
  • inline legend: label of each series are written inline. A background proportional to their value provides additional insight.
  • hover effect: legend will be updated with precise values at the hovered timestamp.

A customized streamgraph built with React and D3.js. It has inline legends, slider to control timeframe, hover effect and more.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Hover effect

It is pretty hard to follow the evolution of a specific group on a streamgraph.

It is common to add an hover effect to the figure: hovering over a group will highlight it, making it easier to follow its evolution. Try it on the graph below:

246810

StreamGraph with hover effect that highlights a specific series

There are various strategies to implement such an hover effect.

Here, I suggest to do everything in css using pseudo classes, and targetting svg elements only. Basically, everything in the svg container will be dimmed (lower opacity and saturation) when the mouse goes over the chart. But the specific shape that is hovered over will keep its full opacity thanks to a more specific css selector.

Hover effect is a big topic and I will post more about it soon!

Know when

Streamgraph inspiration

If you're looking for inspiration to create your next Streamgraph, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Streamgraph looks good!

visit

Streamgraph algorithm with transition

Our streamgraph is renderer using a set of path. The d attribute of those paths provides the boundary coordinates of those paths.

When a prop of the StreamGraph component updates, we might want to update the paths to represent the latest state of our application. It can be an update of the dataset, or an update of the function used to stack the data or smooth the area as below.

It is possible to smoothly animate this transition thanks to react-spring.

Offset typeCurve type
246810

Try d3.js various options to offset the data and smooth shapes. See a smooth transition between options.

The animation suggested above is a bit tricky to implement. Indeed, we need to transition from paths that do not have the same number of edges. It is possible thanks to a library called flubber but definitely deserves its own blogpost.

I'll publish a full blogpost on the topic soon!

Get notified
ToDofind why flubber does some weird interpolation in some cases

Application

The following chart is a real-life application of a streamgraph. It shows the evolution if the number of page-views for 5 tech websites in the last 7 years. My goal was to assess if the rise of chat-GPT had an impact on it.

This interactive chart has several interesting features:

  • slider: you can control the displayed time-frame thanks to a slider.
  • inline legend: label of each series are written inline. A background proportional to their value provides additional insight.
  • hover effect: legend will be updated with precise values at the hovered timestamp.

A customized streamgraph built with React and D3.js. It has inline legends, slider to control timeframe, hover effect and more.

Evolution

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/subscribe.html b/subscribe.html index d389dffb..82cf27a9 100644 --- a/subscribe.html +++ b/subscribe.html @@ -1 +1 @@ -Subscribe

Want more graph examples?


The react graph gallery is a project that just started! If you want to know when a new section gets released, follow me on twitter or subsrcibe below!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +Subscribe

Want more graph examples?


The react graph gallery is a project that just started! If you want to know when a new section gets released, follow me on twitter or subsrcibe below!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/timeseries.html b/timeseries.html index 6acb28dc..6df2d5b2 100644 --- a/timeseries.html +++ b/timeseries.html @@ -1,4 +1,4 @@ -Timeseries| The React Graph Gallery

Timeseries

Dataviz logo representing a Time chart.

This section does not target a specific chart type, even though timeseries are often represented as line charts or area charts.

Instead, it provides a tips and tricks to deal with charts that represent the evolution in time of a numeric variable. For instance, it provides hints on how to deal with dates, how to pan on a chart and more

Useful links

Useful chart types

This page is not about a specific chart type. Instead it provides hints on how to deal with time.

Check the graph sections that are used to visualize timeseries below if there is a specific chart type you want to make.


Picture of a simple heatmap made with react and d3.js

Basic heatmap

Most basic heatmap

Picture of a very simple line chart made with react and d3

Most basic line chart

The most basic line chart one can make using d3 and react

Picture of a basic streamgraph made using Reacrt and d3.js

Basic Streamgraph

Most basic streamgraph one can build using d3 and react

The Date format

The first struggle when dealing with timeseries is to work with the javascript Date format. A Date represents a single moment in time and is usually stored as a string in the input dataset.

Here is an FAQ about the Date format. I constantly forget how this works and come back here for reference. Note that it heavily relies on the d3-time-format module that provides great helpers.

Transform a string into a date

In your dataset, the date of each data point is probably stored as a string, like 2015-06-01 for instance.

In order to manipulate and plot those dates, you need to transform it into a javascript date format.

// import the timeParse function from d3
+Timeseries| The React Graph Gallery

Timeseries

Dataviz logo representing a Time chart.

This section does not target a specific chart type, even though timeseries are often represented as line charts or area charts.

Instead, it provides a tips and tricks to deal with charts that represent the evolution in time of a numeric variable. For instance, it provides hints on how to deal with dates, how to pan on a chart and more

Useful links

Useful chart types

This page is not about a specific chart type. Instead it provides hints on how to deal with time.

Check the graph sections that are used to visualize timeseries below if there is a specific chart type you want to make.


Picture of a simple heatmap made with react and d3.js

Basic heatmap

Most basic heatmap

Picture of a very simple line chart made with react and d3

Most basic line chart

The most basic line chart one can make using d3 and react

Picture of a basic streamgraph made using Reacrt and d3.js

Basic Streamgraph

Most basic streamgraph one can build using d3 and react

The Date format

The first struggle when dealing with timeseries is to work with the javascript Date format. A Date represents a single moment in time and is usually stored as a string in the input dataset.

Here is an FAQ about the Date format. I constantly forget how this works and come back here for reference. Note that it heavily relies on the d3-time-format module that provides great helpers.

Transform a string into a date

In your dataset, the date of each data point is probably stored as a string, like 2015-06-01 for instance.

In order to manipulate and plot those dates, you need to transform it into a javascript date format.

// import the timeParse function from d3
 import { timeParse } from "d3";
 
 // create a time parser function that works for our time format
@@ -38,4 +38,4 @@
 // Use scaleTime() to create a time scale
 const xScale = d3.scaleTime()
   .domain([start, end])
-  .range([0, width]);

Following this code block xScale is a function. You give it a Date, it returns a position in pixels

You can finally use this scale to draw the X axis using your favorite method:

  • create your own react component
  • call d3.axisBottom() in a useEffect

I'm preparing a full post on axes with d3 and react, subscribe to the newsletter if you want to be notified when it's out!

More on axes

A basic time axis build with d3.js and react.

d3 is very smart at picking the right label format. If you're dealing with a very long period of time (years), it will display years. If you're dealing with a month, it will display days. And so on. It is very convenient. The logic controlling this formatting is provided here.

Note that you can customize how dates are formatted along the X axis thanks to the tickFormat function.

Line chart application

If you already understood the content of the line chart section of the gallery, you just have to use a scaleTime instead of a scaleLinear and that's it, you have your first timeseries visualization. πŸ˜‹

Line chart section

A first timeseries line chart made thanks to the scaleTime function of d3.

Synchronized cursor

Another pretty common task when dealing with timeseries is to add a synchronized cursor on all charts.

This makes the dashboard more insightful: hovering over an interesting part of a chart reveals where the timestamp is localized on other charts instantly.

The implementation required to build a shared state between all charts of the webpage. Hovering a specific chart will update this state and thus update all other plots. This process is extensively described in this synchronized cursor for timeseries post.

Read full post

Hover over a chart to see a cursor on both of them, easing the time comparison.

On top of the generic use-cases presented above, here is a gallery of chart examples involving timeseries visualization:


Picture of a timeseries chart made with React and D3.js: scatterplot and line chart in use.

Timeseries with moving average

A scatterplot used for timeseries, with the moving average shown as a line chart on top.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file + .range([0, width]);

Following this code block xScale is a function. You give it a Date, it returns a position in pixels

You can finally use this scale to draw the X axis using your favorite method:

  • create your own react component
  • call d3.axisBottom() in a useEffect

I'm preparing a full post on axes with d3 and react, subscribe to the newsletter if you want to be notified when it's out!

More on axes

A basic time axis build with d3.js and react.

d3 is very smart at picking the right label format. If you're dealing with a very long period of time (years), it will display years. If you're dealing with a month, it will display days. And so on. It is very convenient. The logic controlling this formatting is provided here.

Note that you can customize how dates are formatted along the X axis thanks to the tickFormat function.

Line chart application

If you already understood the content of the line chart section of the gallery, you just have to use a scaleTime instead of a scaleLinear and that's it, you have your first timeseries visualization. πŸ˜‹

Line chart section

A first timeseries line chart made thanks to the scaleTime function of d3.

Synchronized cursor

Another pretty common task when dealing with timeseries is to add a synchronized cursor on all charts.

This makes the dashboard more insightful: hovering over an interesting part of a chart reveals where the timestamp is localized on other charts instantly.

The implementation required to build a shared state between all charts of the webpage. Hovering a specific chart will update this state and thus update all other plots. This process is extensively described in this synchronized cursor for timeseries post.

Read full post

Hover over a chart to see a cursor on both of them, easing the time comparison.

On top of the generic use-cases presented above, here is a gallery of chart examples involving timeseries visualization:


Picture of a timeseries chart made with React and D3.js: scatterplot and line chart in use.

Timeseries with moving average

A scatterplot used for timeseries, with the moving average shown as a line chart on top.

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/treemap.html b/treemap.html index e768bd67..fad11434 100644 --- a/treemap.html +++ b/treemap.html @@ -1,4 +1,4 @@ -Treemap with React

Treemap

Dataviz logo representing a Tree chart.

A treemap displays a hierarchical dataset (a tree) as a set of rectangles. Rectangle sizes are proportional to their numeric value.

d3.js has some handy functions to compute the rectangle positions. React becomes useful to render those rectangles, animate transitions and more. This post explains how to make those 2 tools work together to build a Treemap component.

Useful links

The Data

The dataset describes a hierarchy using a recursive structure. Each item in this structure is called a node, the lowest nodes of the hierarchy being called leaves.

The dataset is an object that has at least 3 properties: name, value and children.children is an array of nodes that have this structure too.


Here is a minimal example of the data structure:

const data = {
+Treemap with React

Treemap

Dataviz logo representing a Tree chart.

A treemap displays a hierarchical dataset (a tree) as a set of rectangles. Rectangle sizes are proportional to their numeric value.

d3.js has some handy functions to compute the rectangle positions. React becomes useful to render those rectangles, animate transitions and more. This post explains how to make those 2 tools work together to build a Treemap component.

Useful links

The Data

The dataset describes a hierarchy using a recursive structure. Each item in this structure is called a node, the lowest nodes of the hierarchy being called leaves.

The dataset is an object that has at least 3 properties: name, value and children.children is an array of nodes that have this structure too.


Here is a minimal example of the data structure:

const data = {
   type: 'node',
   name: "boss",
   value: 2300,
@@ -36,4 +36,4 @@
   const color = colorScale(parentName)
 
   // ... render rect using this color
-}
Mark90Robert12Emily34Marion53Nicolas98Malki22DjΓ©12MΓ©lanie45Einstein76

Treemap with 2 levels of hierarchy and a color scale, made with react and d3.js.

Hover effect

Adding a hover effect to your treemap is a nice polish detail. Here I suggest to highlight the slice that is hovered over by dimming all the other slices.

There are several strategies available to implement such an effect. One can rely on css pseudo classes only, or add a css class using javascript and the onMouseEnter event. It's also possible to rely on an animation library like react-spring.

I'm preparing a full section on the topic. You can subscribe to my dataviz-universe newsletter to know when it will be ready. Meanwhile, there is a code sandbox waiting for you below to reveal the code of this example.

Subscribe
Mark90Robert12Emily34Marion53Nicolas98Malki22DjΓ©12MΓ©lanie45Einstein76

Hover over a group on the treemap to see the other groups fading.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}
Mark90Robert12Emily34Marion53Nicolas98Malki22DjΓ©12MΓ©lanie45Einstein76

Treemap with 2 levels of hierarchy and a color scale, made with react and d3.js.

Hover effect

Adding a hover effect to your treemap is a nice polish detail. Here I suggest to highlight the slice that is hovered over by dimming all the other slices.

There are several strategies available to implement such an effect. One can rely on css pseudo classes only, or add a css class using javascript and the onMouseEnter event. It's also possible to rely on an animation library like react-spring.

I'm preparing a full section on the topic. You can subscribe to my dataviz-universe newsletter to know when it will be ready. Meanwhile, there is a code sandbox waiting for you below to reveal the code of this example.

Subscribe
Mark90Robert12Emily34Marion53Nicolas98Malki22DjΓ©12MΓ©lanie45Einstein76

Hover over a group on the treemap to see the other groups fading.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/typescript-d3-axis.html b/typescript-d3-axis.html index 02870d6b..57f7d39e 100644 --- a/typescript-d3-axis.html +++ b/typescript-d3-axis.html @@ -1,4 +1,4 @@ -Dealing with d3 axis in a typescript environment

D3 axis and typescript

Dataviz logo representing a Lollipop chart.

What is typescript and why it is awesome to use it. How are d3 functions typed.

A few examples on how it works.

Useful links

Most basic linear axis

A graph axis is based on a scale. But what is a scale? This is how thed3-scale module describes it:

Scales are a convenient abstraction for a fundamental task in visualization: mapping a dimension of abstract data to a visual representation

So basically a scale is a function. You provide it with an input like the value of a data point, and it returns another value like a position in pixel.

Here is a very basic implementation of a scale using the scaleLinear function of d3.

const xScale = d3.scaleLinear()
+Dealing with d3 axis in a typescript environment

D3 axis and typescript

Dataviz logo representing a Lollipop chart.

What is typescript and why it is awesome to use it. How are d3 functions typed.

A few examples on how it works.

Useful links

Most basic linear axis

A graph axis is based on a scale. But what is a scale? This is how thed3-scale module describes it:

Scales are a convenient abstraction for a fundamental task in visualization: mapping a dimension of abstract data to a visual representation

So basically a scale is a function. You provide it with an input like the value of a data point, and it returns another value like a position in pixel.

Here is a very basic implementation of a scale using the scaleLinear function of d3.

const xScale = d3.scaleLinear()
   .domain([0, 10]) // data can go from 0 to 10
   .range([0, width]); // it will result in a value that goes from 0 to width
 
@@ -20,4 +20,4 @@
 // Color scale
 const colorScale = d3.scaleOrdinal<string>()
   .domain(allGroups)
-  .range(COLORS);

You can see how scaleOrdinal type implementation

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file + .range(COLORS);

You can see how scaleOrdinal type implementation

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/violin-plot.html b/violin-plot.html index 777dc393..a86f00e4 100644 --- a/violin-plot.html +++ b/violin-plot.html @@ -1,4 +1,4 @@ -Violin plot with React

Violin plot

Dataviz logo representing a Violin chart.

A violin chart displays the distribution of a numeric variable, often for several groups of a dataset. This page is a step-by-step guide on how to build your own violin component for the web, using React and D3.js.

It starts by describing how the data should be organized and how to initialize the violin component. D3.js is then used to split the data in buckets thanks to the bin() function. It then adds smoothing to it with curve(). React is finally used to render the violin using a SVG path.

Useful links

The Data πŸ’Ύ

The dataset used to build a violin chart is usually an array of object. For each object, a name property provides the group name, and a value property provides the numeric value. It looks like this:

const data = [
+Violin plot with React

Violin plot

Dataviz logo representing a Violin chart.

A violin chart displays the distribution of a numeric variable, often for several groups of a dataset. This page is a step-by-step guide on how to build your own violin component for the web, using React and D3.js.

It starts by describing how the data should be organized and how to initialize the violin component. D3.js is then used to split the data in buckets thanks to the bin() function. It then adds smoothing to it with curve(). React is finally used to render the violin using a SVG path.

Useful links

The Data πŸ’Ύ

The dataset used to build a violin chart is usually an array of object. For each object, a name property provides the group name, and a value property provides the numeric value. It looks like this:

const data = [
   { name: "A", value: 10.7577 },
   { name: "A", value: 19.9273 },
   { name: "B", value: 13.8917 },
@@ -144,4 +144,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Violin inspiration

If you're looking for inspiration to create your next Violin, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Violin looks good!

visit

Effect of the bucket size

It's important to understand that under the hood, a violin shape is nothing else than a smoothed histogram. You can use the sentence below the following chart to switch from one to the other and understand the tight connection.

As a result the violin plot suffers the same flaw as the histogram: its shape highly depends on the number of buckets used for the computation. Use the slider to see the impact of the target bucket number on the violin shape.

Each violin shape based on approx. 5 buckets
-10-505101520253035ABCD
You can use smoothing or steps.

Interactive violin plot: try to toggle smoothing and change the number of buckets in use.

Note: the requested number of buckets is a target. The bin() function of d3 will create smart buckets around this value.

Comparison with a boxplot

The boxplot is an alternative to represent the exact same kind of dataset. You can visit the boxplot section of the gallery or play with the interactive example below to understand how those 2 options behave on the same dataset.

Use the slider to switch from the violin to the box. Play with the sentence below the chart to toggle smoothing on the violin.

-10-505101520253035ABCD
You can use smoothing or steps.

Compare how violins and boxplots look like for the same dataset.

Animation

Animating the transition between 2 datasets, or from/to another chart type is hard, because the violin plot is based on SVG path. It is doable though and I'm working on a specific post that will be released soon.

schema explaining how histogram buckets are created from the original dataset

Using shape morphism to transition between a boxplot and a violin plot. Blog post coming soon!

If you're interested in this topic, feel free to subscribe to the newsletter to be informed when this post is available!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Violin inspiration

If you're looking for inspiration to create your next Violin, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Violin looks good!

visit

Effect of the bucket size

It's important to understand that under the hood, a violin shape is nothing else than a smoothed histogram. You can use the sentence below the following chart to switch from one to the other and understand the tight connection.

As a result the violin plot suffers the same flaw as the histogram: its shape highly depends on the number of buckets used for the computation. Use the slider to see the impact of the target bucket number on the violin shape.

Each violin shape based on approx. 5 buckets
-10-505101520253035ABCD
You can use smoothing or steps.

Interactive violin plot: try to toggle smoothing and change the number of buckets in use.

Note: the requested number of buckets is a target. The bin() function of d3 will create smart buckets around this value.

Comparison with a boxplot

The boxplot is an alternative to represent the exact same kind of dataset. You can visit the boxplot section of the gallery or play with the interactive example below to understand how those 2 options behave on the same dataset.

Use the slider to switch from the violin to the box. Play with the sentence below the chart to toggle smoothing on the violin.

-10-505101520253035ABCD
You can use smoothing or steps.

Compare how violins and boxplots look like for the same dataset.

Animation

Animating the transition between 2 datasets, or from/to another chart type is hard, because the violin plot is based on SVG path. It is doable though and I'm working on a specific post that will be released soon.

schema explaining how histogram buckets are created from the original dataset

Using shape morphism to transition between a boxplot and a violin plot. Blog post coming soon!

If you're interested in this topic, feel free to subscribe to the newsletter to be informed when this post is available!

Distribution

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/viz-from-the-future.html b/viz-from-the-future.html index e6d5bcf6..47d673d3 100644 --- a/viz-from-the-future.html +++ b/viz-from-the-future.html @@ -1 +1 @@ -How to build a responsive chart with React and d3.js

A viz from the future


Building a viz from the future?

-What is a viz from the future?

You know minority report?

This video is what I mean

  • Dark mode
  • Flashy, Neon color
  • Glowing shapes
  • Gradient
  • Animation

-Glowing div with box-shadow

Can be done with overlapping box-shadow.

Official doc is here

A box shadow is described by X and Y offsets relative to the element, blur and spread radius, and color.

With inset, I can put the shadow inside of the shape

shadows are drawn one of top of each other.

But there is an issue: box-shadow does not exist for svg.

-Glowing svg with ...

How can I do.

Two main ways: svg filter and css filter

css filter is easy, it works like box-shadows that is described above

BUT, it does not work with inset, so we need another solution for inside shadow.

But there is an issue: how to do for canvas




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +How to build a responsive chart with React and d3.js

A viz from the future


Building a viz from the future?

-What is a viz from the future?

You know minority report?

This video is what I mean

  • Dark mode
  • Flashy, Neon color
  • Glowing shapes
  • Gradient
  • Animation

-Glowing div with box-shadow

Can be done with overlapping box-shadow.

Official doc is here

A box shadow is described by X and Y offsets relative to the element, blur and spread radius, and color.

With inset, I can put the shadow inside of the shape

shadows are drawn one of top of each other.

But there is an issue: box-shadow does not exist for svg.

-Glowing svg with ...

How can I do.

Two main ways: svg filter and css filter

css filter is easy, it works like box-shadows that is described above

BUT, it does not work with inset, so we need another solution for inside shadow.

But there is an issue: how to do for canvas




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/voronoi.html b/voronoi.html index 7dcb9575..49168d26 100644 --- a/voronoi.html +++ b/voronoi.html @@ -1,4 +1,4 @@ -How to build a Voronoi Diagram with React and D3.

Voronoi Diagram

Dataviz logo representing a Voronoi chart.

A voronoi diagram is a partition of a plane into regions called voronoi cells. A voronoi cell consists of every point in the plane whose distance to its linked data point is less than or equal to its distance to any other data point.

This page is a step-by-step guide on how to build your own voronoi diagram for the web, using React and D3.js.

It starts by describing how the data should be organized and explains how to run and plot a Delaunay triangulation. Based on this, it explains how to build the voronoi diagram. Finally it shows how this can be used for real life application like for a scatterplot or to build a voronoi treemap.

Useful links

The Data

Everything starts with a set of two-dimensional points. Their coordinates are available with x representing the position on the horizontal axis and y being for the vertical axis.

As a result, the dataset is pretty simple: an array of objects that looks like this:


export const data = [
+How to build a Voronoi Diagram with React and D3.

Voronoi Diagram

Dataviz logo representing a Voronoi chart.

A voronoi diagram is a partition of a plane into regions called voronoi cells. A voronoi cell consists of every point in the plane whose distance to its linked data point is less than or equal to its distance to any other data point.

This page is a step-by-step guide on how to build your own voronoi diagram for the web, using React and D3.js.

It starts by describing how the data should be organized and explains how to run and plot a Delaunay triangulation. Based on this, it explains how to build the voronoi diagram. Finally it shows how this can be used for real life application like for a scatterplot or to build a voronoi treemap.

Useful links

The Data

Everything starts with a set of two-dimensional points. Their coordinates are available with x representing the position on the horizontal axis and y being for the vertical axis.

As a result, the dataset is pretty simple: an array of objects that looks like this:


export const data = [
   { x: 10, y: 10 },
   { x: 4, y: 4 },
   { x: 35, y: 90 },
@@ -36,4 +36,4 @@
   }, []);
 
   return dimensions;
-}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Voronoi inspiration

If you're looking for inspiration to create your next Voronoi, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Voronoi looks good!

visit

Closest point detection

The voronoi diagram is commonly used to detect the closest data point of the mouse position. This can be pretty useful to highlight the closest point without having to hover exactly over it.

In the example below, the closest dot will be highlighted with a red circle ⭕️ using the voronoi cells.


Use the voronoi algorithm to detect the closest point of the mouse position.

Variations

A glimpse of what it is possible to do using the voronoi diagram for data visualization.

Click on the overview below to get details and code.


gif of a scatterplot with voronoi diagram for closest point detection

Closest point detection with Voronoi

Using a voronoi diagram in the scatterplot background is a smart way to efficiently find the mouse closest point

ToDoAdd voronoi treemap example

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +}

I'm in the process of writing a complete blog post on the topic. Subscribe to the project to know when it's ready.




Voronoi inspiration

If you're looking for inspiration to create your next Voronoi, note that dataviz-inspiration.com showcases many examples. Definitely the best place to get ... inspiration!

dataviz-inspiration.com showcases hundreds of stunning dataviz projects. Have a look to get some ideas on how to make your Voronoi looks good!

visit

Closest point detection

The voronoi diagram is commonly used to detect the closest data point of the mouse position. This can be pretty useful to highlight the closest point without having to hover exactly over it.

In the example below, the closest dot will be highlighted with a red circle ⭕️ using the voronoi cells.


Use the voronoi algorithm to detect the closest point of the mouse position.

Variations

A glimpse of what it is possible to do using the voronoi diagram for data visualization.

Click on the overview below to get details and code.


gif of a scatterplot with voronoi diagram for closest point detection

Closest point detection with Voronoi

Using a voronoi diagram in the scatterplot background is a smart way to efficiently find the mouse closest point

ToDoAdd voronoi treemap example

Part Of A Whole

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/what-is-a-color.html b/what-is-a-color.html index 17a9967e..7cbf8508 100644 --- a/what-is-a-color.html +++ b/what-is-a-color.html @@ -1 +1 @@ -What is a color

What is a color


There are so many ways to define a color when talking with a computer. Let's take a tour and see what's the most appropriate in a dataviz point of view.

-Color on screen

A computer screen is made of thousands of pixels.

Each pixel generates three colors of light (red, green, and blue) and the different colors we see are due to different combinations and intensities of these three primary colors.

red, green and blue are the primary colors.

-The RGB color model

The color information for each pixel is typically stored in a 24-bit format: 8 bit per primary color. This is 2^8 = 256 possibilities for each primary color. This means more than 16M possible color variations for each pixel (256^3)!

-The HSV, HSL and HSB color model

That's the famous color wheel you see in every color picker!


On colorpicker.me you can define a color using its hue (vertical bar), its saturation (x axis of the square) and its lightness (vertical axis)

HSL stands for hue, saturation, lightness

HSV and HSB are the same and stand for hue, saturation, value or hue, saturation, brightness respectively.

But what does it even mean?

  • Hue: the initial color. Between 0 and 360.
  • Saturation: when closer to 100, the color shines. represents how β€œcolorful” the color is. Intensity. Purity. When 0, you get grey
  • Lighness, Value, Brightness

The color cylinder of HSV

There are an alternative to the RGB color model to more closely align with the way human vision perceives color-making attributes

Indeed, it allows us to describe meaningful relationships between colors. For instance, to create 2 complementary colors you can select 2 colors on the opposite side of the wheel, with same saturation and brithness. Same principle for analogous, monochrome palette and other famous combinations.

HSV is criticized. This is because in HSV the V (value) is just a measure for the physical lightness of color, but not for the perceived brightness. So 2 colors with the same value are not perceive with the same lightness by the Human Eye. There is a hue-dependency of brightness in this model.

Note: pastel color = high lightness and low saturation.

-The CIELAB color model

Try to fix this difference between computer and human perception.

unintuitive to use to generate colors

The cielab color space

-The HCL color model

Stands for Hue-Chroma-Lightness. A cylindrical transformation of CIE Lab*

-The luminance of a color

TODO

-Contrast ratio

The Web Content Accessibility Guidelines (WCAG) include convenient quantitative recommendations for making a color accessible based on the minimum acceptable contrast of foreground against background.

Basically, you can compare the luminance of 2 colors and compute their contrast ratio. The luminance is computed using the amount of red, green and blue in it.

To see the exact formulas and compute the contrast ratio between 2 colors, see this notebook by Mike Bostock


A tool to compute the contrast ratio between 2 colors.

Note: the notebook provides the d3 code to compute this contrast ratio.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file +What is a color

What is a color


There are so many ways to define a color when talking with a computer. Let's take a tour and see what's the most appropriate in a dataviz point of view.

-Color on screen

A computer screen is made of thousands of pixels.

Each pixel generates three colors of light (red, green, and blue) and the different colors we see are due to different combinations and intensities of these three primary colors.

red, green and blue are the primary colors.

-The RGB color model

The color information for each pixel is typically stored in a 24-bit format: 8 bit per primary color. This is 2^8 = 256 possibilities for each primary color. This means more than 16M possible color variations for each pixel (256^3)!

-The HSV, HSL and HSB color model

That's the famous color wheel you see in every color picker!


On colorpicker.me you can define a color using its hue (vertical bar), its saturation (x axis of the square) and its lightness (vertical axis)

HSL stands for hue, saturation, lightness

HSV and HSB are the same and stand for hue, saturation, value or hue, saturation, brightness respectively.

But what does it even mean?

  • Hue: the initial color. Between 0 and 360.
  • Saturation: when closer to 100, the color shines. represents how β€œcolorful” the color is. Intensity. Purity. When 0, you get grey
  • Lighness, Value, Brightness

The color cylinder of HSV

There are an alternative to the RGB color model to more closely align with the way human vision perceives color-making attributes

Indeed, it allows us to describe meaningful relationships between colors. For instance, to create 2 complementary colors you can select 2 colors on the opposite side of the wheel, with same saturation and brithness. Same principle for analogous, monochrome palette and other famous combinations.

HSV is criticized. This is because in HSV the V (value) is just a measure for the physical lightness of color, but not for the perceived brightness. So 2 colors with the same value are not perceive with the same lightness by the Human Eye. There is a hue-dependency of brightness in this model.

Note: pastel color = high lightness and low saturation.

-The CIELAB color model

Try to fix this difference between computer and human perception.

unintuitive to use to generate colors

The cielab color space

-The HCL color model

Stands for Hue-Chroma-Lightness. A cylindrical transformation of CIE Lab*

-The luminance of a color

TODO

-Contrast ratio

The Web Content Accessibility Guidelines (WCAG) include convenient quantitative recommendations for making a color accessible based on the minimum acceptable contrast of foreground against background.

Basically, you can compare the luminance of 2 colors and compute their contrast ratio. The luminance is computed using the amount of red, green and blue in it.

To see the exact formulas and compute the contrast ratio between 2 colors, see this notebook by Mike Bostock


A tool to compute the contrast ratio between 2 colors.

Note: the notebook provides the d3 code to compute this contrast ratio.




Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file diff --git a/wordcloud.html b/wordcloud.html index 91708b56..f28f73c9 100644 --- a/wordcloud.html +++ b/wordcloud.html @@ -1,4 +1,4 @@ -Wordcloud with React

Wordcloud

Dataviz logo representing a Wordcloud chart.

This page explains how to build a wordcloud using react and d3.js. It uses the d3-cloud plugin to compute the position of each word, and render them with react.

This section is rather short as I'm not a big fan of wordclouds. They can be quite misleading and you should consider building a barplot or a lollipop plot instead.

Useful links
This page uses the d3-cloud plugin that you can install in your project with npm install d3-cloud

The Data

The data is an array. Each item is an object describing a word. Its name is provided, together with a related value that will be used to size the word on the final figure.

Note that you can add any additional property here, like a color, a font weight or anything else that you want to use to draw the word later on.

const data = [
+Wordcloud with React

Wordcloud

Dataviz logo representing a Wordcloud chart.

This page explains how to build a wordcloud using react and d3.js. It uses the d3-cloud plugin to compute the position of each word, and render them with react.

This section is rather short as I'm not a big fan of wordclouds. They can be quite misleading and you should consider building a barplot or a lollipop plot instead.

Useful links
This page uses the d3-cloud plugin that you can install in your project with npm install d3-cloud

The Data

The data is an array. Each item is an object describing a word. Its name is provided, together with a related value that will be used to size the word on the final figure.

Note that you can add any additional property here, like a color, a font weight or anything else that you want to use to draw the word later on.

const data = [
   { text: "hello", value: 12 },
   { text: "world", value: 2 },
 ];

Most basic wordcloud with React and D3.js

Everything starts by instantiating a wordcloud layout using thed3Cloud() function of the d3-cloud library.

const layout = d3Cloud()
@@ -8,4 +8,4 @@
   .padding(10)
   .on("end", (words) => {
     setWordsPosition(words);
-  });

This layout can then be called from a useEffect using layout.start(). The layout algorithm will loop through each word of the dataset and try to place them on the chart, avoiding overlaps with other words.

Once the loop is over, the layout algorithm will produce a words object and provide it to the end() function. This function update a state that stores the position and feature of each word.

It is thus possible to map through those word features and draw them using html, svg or canvas. Here is an example using HTML


Most basic Wordcloud made with react and d3.js

Todo: write better explanation
Todo: the layout algorithm currently provides unperfect values, resulting in a lot of word overlaps. Please tell me if you find where the bug is.

Warning

Wordclouds are useful for quickly perceiving the most prominent terms. They are widely used in media and well understood by the public. However, they are criticized for 2 main reasons:

  • Area is a poor metaphor of a numeric value, it is hardly perceive by the human eye
  • Longer words appear bigger by construction

To put it in a nutshell, wordclouds must be avoided. You can read more about that in data-to-viz. Why not consider a lollipop plot or a barplot instead?

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file + });

This layout can then be called from a useEffect using layout.start(). The layout algorithm will loop through each word of the dataset and try to place them on the chart, avoiding overlaps with other words.

Once the loop is over, the layout algorithm will produce a words object and provide it to the end() function. This function update a state that stores the position and feature of each word.

It is thus possible to map through those word features and draw them using html, svg or canvas. Here is an example using HTML


Most basic Wordcloud made with react and d3.js

Todo: write better explanation
Todo: the layout algorithm currently provides unperfect values, resulting in a lot of word overlaps. Please tell me if you find where the bug is.

Warning

Wordclouds are useful for quickly perceiving the most prominent terms. They are widely used in media and well understood by the public. However, they are criticized for 2 main reasons:

  • Area is a poor metaphor of a numeric value, it is hardly perceive by the human eye
  • Longer words appear bigger by construction

To put it in a nutshell, wordclouds must be avoided. You can read more about that in data-to-viz. Why not consider a lollipop plot or a barplot instead?

Contact

πŸ‘‹ Hey, I'm Yan and I'm currently working on this project!

Feedback is welcome ❀️. You can fill an issue on Github, drop me a message on Twitter, or even send me an email pasting yan.holtz.data with gmail.com. You can also subscribe to the newsletter to know when I publish more content!

\ No newline at end of file