Skip to content

Instantly share code, notes, and snippets.

@the-teacher
Forked from evuez/donutchart.rb
Created March 15, 2017 08:27
Show Gist options
  • Save the-teacher/39488f2010a0d1070f45767558f0de33 to your computer and use it in GitHub Desktop.
Save the-teacher/39488f2010a0d1070f45767558f0de33 to your computer and use it in GitHub Desktop.
Donut chart generator
def donut(data, size, thickness, background='#fff')
cx = cy = size / 2
radius = size / 2 - 2
sum = data.values.inject(:+)
dx = 0
dy = -radius
angle = -90
paths = ''
data.each do |klass, value|
_angle = angle + value / (sum / 360.0)
x = Math.cos(_angle * Math::PI / 180) * radius
y = Math.sin(_angle * Math::PI / 180) * radius
ax, ay = cx + x, cy + y
adx, ady = cx + dx, cy + dy
paths << %Q{
<path
class="#{klass} donut__slice"
d="
M#{cx},#{cy}
L#{adx},#{ady}
A#{radius},#{radius} 0 %{laf},1 #{ax},#{ay}z
"
/>
} % {laf: value > sum / 2.0 ? 1 : 0}
dx, dy = x, y
angle = _angle
end
paths << %Q{
<circle
class="donut__hole"
cx="#{cx}" cy="#{cy}" r="%{radius}"
fill="#{background}"
/>
} % {radius: radius - thickness}
%Q{
<svg width="#{size}px" height="#{size}px" class="donut" xmlns="http://www.w3.org/2000/svg">
#{paths}
</svg>
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment