Skip to main content
100%

Reusable Donut Chart in D3 v4

✓ Published0🌍 Public
TThanaporn-sk
Last edited Jul 28, 2017
Created on Jul 28, 2017

This donut chart displays species probability data from a TSV file, with each slice colored by species and labeled with its percentage. The chart is implemented as a reusable D3.js v4 function, using `d3.pie()` to compute slice angles, `d3.arc()` for rendering with configurable corner radius and padding, and `d3.scaleOrdinal()` with a categorical color scheme. Hovering over a slice or its label shows a tooltip with the species name and percentage in the donut’s center—a feature built from D3’s selection and event handling. The SVG output includes text labels and connecting polylines, styled via CSS.

AI-generated description

I'm relatively new to d3.js and know it can be tough getting started as a lot of bl.ocks and tutorials don't have what I would consider adequate comments.

One of the first real-world problems I had to tackle with d3 was a donut chart (which would eventually need to be dynamic).
I flew around stackoverflow, google, bl.ocks, and everything inbetween trying to get my head around how to make one. I eventually got something up and running but the code was a bowl of spaghetti and I had no idea how it was actually working.

What I decided to do in the end was to start with a clean slate and build the pieces one-by-one. I have been helped immensely by juancb's bl.ock and the Pie Chart Update series by Mike Bostock.

Two of the main goals I wanted to achieve with making this were:

  1. Make the chart reusable. Which, in my opinion, is one of the most important concepts in d3.
  2. Make it using d3 v4, as most tutorials I come across are still in d3 v3.

Going through the process of making a chart reusable really helps in understanding how all the pieces fit together and boosts your understanding of how charts are constructed.

I worked through the tutorials mentioned above until I understood (pretty much) every line of code. I went to town on the comments because:

  • I will be very thankful for it in 6 months time.
  • I hope it will help out someone else in my position 3 months ago.

This donut chart has a tooltip that appears in the centre of the donut when the mouse enters a chart slice or hovers over a species name. By making the chart in this reusable fashion I think you should be able to easily tweak any settings to meet your needs. If you do need any help or advise with this those feel free to get in touch.

This is my first bl.ock so please let me know if there are any issues or things I can improve on.
I am also working on a dynamic, updating version of this so I will add and link that when it is done.

Next: Dynamic, reusable chart.

forked from <a href='http://bl.ocks.org/mbhall88/'>mbhall88</a>'s block: <a href='http://bl.ocks.org/mbhall88/b2504f8f3e384de4ff2b9dfa60f325e2'>A static, reusable donut chart for D3.js v4.</a>

mit Licensed

Similar vizzes