Here we use some data from my Knowledge Base database of books to display the top 5 subject headings as a donut chart.
Typically the data would be pulled from a database, which would then make this script dynamic (I don't have to update it every time the DB is changed).
The data would then be mangled into shape to be displayed as SVG. However in this case I hard-coded the data.
Total # of resources (Books & Articles): 352 (from my Knowledge Base library).
The 5 keywords, number, color used:
Note that these keywords and numbers represent only a small fraction of the total number of keywords, and their numbers. There are 273 unique keywords and 812 resources. This is important when we do the math later.
If you view the source code (recommended) you may notice a few new things. SVG text can be mangled, almost like CSS. In this example I use font-family="Chalkboard SE" and also change the size font-size="20". In SVG the font size is assumed to be in pixels, so no unit type is needed.
The arrays holding keywords, colors, and numbers are sorted by number in descending order. The arrays are in the same order so we can use an index in a loop, thus ensuring everything matches up.
For example, to print the SVG to create the small circles and text in the middle, for each keyword, had to be done like this, in a loop:
As mentioned, a lot of variables are used: ndx, thisQty, TotalQty, thisColor, r, cx, cy, Colors[ndx], X, Y, Qty[ndx], CX, CY, R, thisAngle, StartAngle, EndAngle.
'ThisVariable' is NOT the same as 'thisVariable'
Wherever a variable is used, it can't be printed directly, but must be quoted.
My advice ... Be patient and VERY careful. It will be worth it.
A final note on how this works. Building up the donut this way, the first arc begins at 0° (12:00). But where does it end? Ahh, for that we need thisAngle, StartAngle and EndAngle.
First we need thisAngle which is determined by the current keyword quantity, divided by the total quantity, multiplied by 360. (convert the keyword quantity into a degree value)
EndAngle is determined by adding thisAngle to StartAngle.
Finally we set the next StartAngle to the current EndAngle, and add StartAngle to the current EndAngle.