Skip to content

Instantly share code, notes, and snippets.

@evuez
Last active November 29, 2017 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save evuez/61bb9012d459cfb1330e to your computer and use it in GitHub Desktop.
Save evuez/61bb9012d459cfb1330e 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
@abhayathapa
Copy link

Could you please provide an example with working data and colorful donut chart. Thanks in advance

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment