Hello. I am trying to learn how to create a pie chart using SVG.
The key is that the solution needs to handle multiple slices. (There are lots of tutorials on how to do a simple CSS pie chart with just two halves, but that isn’t what I need.)
I have spent the last couple of weeks reading up on SVG, but there aren’t any really good tutorials/solutions on this particular problem…
Here is a link to a solution that looks promising, but I don’t completely understand the code, and it doesn’t seem like it has any math behind it. (These pie charts are for a business, so “hacking” things until they look “close” won’t do!)
https://codepen.io/hari2609/full/LmEzOm
How does the following code work…
<circle r="25%" cx="50%" cy="50%" style="stroke-dasharray: 75.3 100"></circle>
Here is what I think is going on…
-
You create a ViewBox starting at 0, 0 and which has a grid of 64 x 64.
-
You resize the final results to 300px X 300px using CSS
-
You give the SVG a border-radius of 50% making it a circle. (Not sure why this is needed as you have a
<circle>
below?) -
You create an SVG
<circle>
centered in the middle of the grid -
It has a radius of 25% which makes a circle that is 1/2 the width and height of the parent SVG canvas. (The “circle” is more like a “ring”.)
-
You give the
<circle>
astroke-width
of 32 which adds a border to the aforementioned circle that is so wide that the circle “ring” becomes a filled circle that has a radius of 32 units. -
The gold stroke makes it a gold filled circle.
Now for the part that escapes me…
- You add a
stroke-array: 75.3 100
Questions:
Q1.) How does stroke-array: 75.3 100
end up drawing a pie-chart SLICE that is roughly three-quarters of the entire pie?
Q2.) And how does the modified code of stroke-array: 50.3 100
yield a SLICE that is roughly one-half that of the entire pie?
Q3.) Is there a way to create slices using a more mathematical/geometric methd?
Again, I need pie slices that accurately display precise percentages (e.g. 47.5%, 25%, 12.5%, 8.4%, 6.6%) and that ultimately visually add up to a whole pie (i.e. 100%).
Thanks.
P.S. It is also important to come up with an SVG solution that can be programmed in PHP on the server. So, even though I could draw the Statue of Liberty using SVG paths, that isn’t practical to program! The hope is that i can query MySQL, build a result-set that is basically a table of Category-Value pairs, and then use those values to drive how big each pie-slice is. (If I can figure out the code above, it seems like a simple enough way to program in PHP.)