Debian Codegraph @

pie_chart.go

raw symbols SCIP
1 package chart
2
3 import (
4 "errors"
5 "fmt"
6 "io"
7
8 "github.com/golang/freetype/truetype"
9 )
10
11 // PieChart is a chart that draws sections of a circle based on percentages.
12 type PieChart struct {
13 Title string
14 TitleStyle Style
15
16 ColorPalette ColorPalette
17
18 Width int
19 Height int
20 DPI float64
21
22 Background Style
23 Canvas Style
24 SliceStyle Style
25
26 Font *truetype.Font
27 defaultFont *truetype.Font
28
29 Values []Value
30 Elements []Renderable
31 }
32
33 // GetDPI returns the dpi for the chart.
34 func (pc PieChart) GetDPI(defaults ...float64) float64 {
35 if pc.DPI == 0 {
36 if len(defaults) > 0 {
37 return defaults[0]
38 }
39 return DefaultDPI
40 }
41 return pc.DPI
42 }
43
44 // GetFont returns the text font.
45 func (pc PieChart) GetFont() *truetype.Font {
46 if pc.Font == nil {
47 return pc.defaultFont
48 }
49 return pc.Font
50 }
51
52 // GetWidth returns the chart width or the default value.
53 func (pc PieChart) GetWidth() int {
54 if pc.Width == 0 {
55 return DefaultChartWidth
56 }
57 return pc.Width
58 }
59
60 // GetHeight returns the chart height or the default value.
61 func (pc PieChart) GetHeight() int {
62 if pc.Height == 0 {
63 return DefaultChartWidth
64 }
65 return pc.Height
66 }
67
68 // Render renders the chart with the given renderer to the given io.Writer.
69 func (pc PieChart) Render(rp RendererProvider, w io.Writer) error {
70 if len(pc.Values) == 0 {
71 return errors.New("please provide at least one value")
72 }
73
74 r, err := rp(pc.GetWidth(), pc.GetHeight())
75 if err != nil {
76 return err
77 }
78
79 if pc.Font == nil {
80 defaultFont, err := GetDefaultFont()
81 if err != nil {
82 return err
83 }
84 pc.defaultFont = defaultFont
85 }
86 r.SetDPI(pc.GetDPI(DefaultDPI))
87
88 canvasBox := pc.getDefaultCanvasBox()
89 canvasBox = pc.getCircleAdjustedCanvasBox(canvasBox)
90
91 pc.drawBackground(r)
92 pc.drawCanvas(r, canvasBox)
93
94 finalValues, err := pc.finalizeValues(pc.Values)
95 if err != nil {
96 return err
97 }
98 pc.drawSlices(r, canvasBox, finalValues)
99 pc.drawTitle(r)
100 for _, a := range pc.Elements {
101 a(r, canvasBox, pc.styleDefaultsElements())
102 }
103
104 return r.Save(w)
105 }
106
107 func (pc PieChart) drawBackground(r Renderer) {
108 Draw.Box(r, Box{
109 Right: pc.GetWidth(),
110 Bottom: pc.GetHeight(),
111 }, pc.getBackgroundStyle())
112 }
113
114 func (pc PieChart) drawCanvas(r Renderer, canvasBox Box) {
115 Draw.Box(r, canvasBox, pc.getCanvasStyle())
116 }
117
118 func (pc PieChart) drawTitle(r Renderer) {
119 if len(pc.Title) > 0 && !pc.TitleStyle.Hidden {
120 Draw.TextWithin(r, pc.Title, pc.Box(), pc.styleDefaultsTitle())
121 }
122 }
123
124 func (pc PieChart) drawSlices(r Renderer, canvasBox Box, values []Value) {
125 cx, cy := canvasBox.Center()
126 diameter := MinInt(canvasBox.Width(), canvasBox.Height())
127 radius := float64(diameter >> 1)
128 labelRadius := (radius * 2.0) / 3.0
129
130 // draw the pie slices
131 var rads, delta, delta2, total float64
132 var lx, ly int
133
134 if len(values) == 1 {
135 pc.stylePieChartValue(0).WriteToRenderer(r)
136 r.MoveTo(cx, cy)
137 r.Circle(radius, cx, cy)
138 } else {
139 for index, v := range values {
140 v.Style.InheritFrom(pc.stylePieChartValue(index)).WriteToRenderer(r)
141
142 r.MoveTo(cx, cy)
143 rads = PercentToRadians(total)
144 delta = PercentToRadians(v.Value)
145
146 r.ArcTo(cx, cy, radius, radius, rads, delta)
147
148 r.LineTo(cx, cy)
149 r.Close()
150 r.FillStroke()
151 total = total + v.Value
152 }
153 }
154
155 // draw the labels
156 total = 0
157 for index, v := range values {
158 v.Style.InheritFrom(pc.stylePieChartValue(index)).WriteToRenderer(r)
159 if len(v.Label) > 0 {
160 delta2 = PercentToRadians(total + (v.Value / 2.0))
161 delta2 = RadianAdd(delta2, _pi2)
162 lx, ly = CirclePoint(cx, cy, labelRadius, delta2)
163
164 tb := r.MeasureText(v.Label)
165 lx = lx - (tb.Width() >> 1)
166 ly = ly + (tb.Height() >> 1)
167
168 if lx < 0 {
169 lx = 0
170 }
171 if ly < 0 {
172 lx = 0
173 }
174
175 r.Text(v.Label, lx, ly)
176 }
177 total = total + v.Value
178 }
179 }
180
181 func (pc PieChart) finalizeValues(values []Value) ([]Value, error) {
182 finalValues := Values(values).Normalize()
183 if len(finalValues) == 0 {
184 return nil, fmt.Errorf("pie chart must contain at least (1) non-zero value")
185 }
186 return finalValues, nil
187 }
188
189 func (pc PieChart) getDefaultCanvasBox() Box {
190 return pc.Box()
191 }
192
193 func (pc PieChart) getCircleAdjustedCanvasBox(canvasBox Box) Box {
194 circleDiameter := MinInt(canvasBox.Width(), canvasBox.Height())
195
196 square := Box{
197 Right: circleDiameter,
198 Bottom: circleDiameter,
199 }
200
201 return canvasBox.Fit(square)
202 }
203
204 func (pc PieChart) getBackgroundStyle() Style {
205 return pc.Background.InheritFrom(pc.styleDefaultsBackground())
206 }
207
208 func (pc PieChart) getCanvasStyle() Style {
209 return pc.Canvas.InheritFrom(pc.styleDefaultsCanvas())
210 }
211
212 func (pc PieChart) styleDefaultsCanvas() Style {
213 return Style{
214 FillColor: pc.GetColorPalette().CanvasColor(),
215 StrokeColor: pc.GetColorPalette().CanvasStrokeColor(),
216 StrokeWidth: DefaultStrokeWidth,
217 }
218 }
219
220 func (pc PieChart) styleDefaultsPieChartValue() Style {
221 return Style{
222 StrokeColor: pc.GetColorPalette().TextColor(),
223 StrokeWidth: 5.0,
224 FillColor: pc.GetColorPalette().TextColor(),
225 }
226 }
227
228 func (pc PieChart) stylePieChartValue(index int) Style {
229 return pc.SliceStyle.InheritFrom(Style{
230 StrokeColor: ColorWhite,
231 StrokeWidth: 5.0,
232 FillColor: pc.GetColorPalette().GetSeriesColor(index),
233 FontSize: pc.getScaledFontSize(),
234 FontColor: pc.GetColorPalette().TextColor(),
235 Font: pc.GetFont(),
236 })
237 }
238
239 func (pc PieChart) getScaledFontSize() float64 {
240 effectiveDimension := MinInt(pc.GetWidth(), pc.GetHeight())
241 if effectiveDimension >= 2048 {
242 return 48.0
243 } else if effectiveDimension >= 1024 {
244 return 24.0
245 } else if effectiveDimension > 512 {
246 return 18.0
247 } else if effectiveDimension > 256 {
248 return 12.0
249 }
250 return 10.0
251 }
252
253 func (pc PieChart) styleDefaultsBackground() Style {
254 return Style{
255 FillColor: pc.GetColorPalette().BackgroundColor(),
256 StrokeColor: pc.GetColorPalette().BackgroundStrokeColor(),
257 StrokeWidth: DefaultStrokeWidth,
258 }
259 }
260
261 func (pc PieChart) styleDefaultsElements() Style {
262 return Style{
263 Font: pc.GetFont(),
264 }
265 }
266
267 func (pc PieChart) styleDefaultsTitle() Style {
268 return pc.TitleStyle.InheritFrom(Style{
269 FontColor: pc.GetColorPalette().TextColor(),
270 Font: pc.GetFont(),
271 FontSize: pc.getTitleFontSize(),
272 TextHorizontalAlign: TextHorizontalAlignCenter,
273 TextVerticalAlign: TextVerticalAlignTop,
274 TextWrap: TextWrapWord,
275 })
276 }
277
278 func (pc PieChart) getTitleFontSize() float64 {
279 effectiveDimension := MinInt(pc.GetWidth(), pc.GetHeight())
280 if effectiveDimension >= 2048 {
281 return 48
282 } else if effectiveDimension >= 1024 {
283 return 24
284 } else if effectiveDimension >= 512 {
285 return 18
286 } else if effectiveDimension >= 256 {
287 return 12
288 }
289 return 10
290 }
291
292 // GetColorPalette returns the color palette for the chart.
293 func (pc PieChart) GetColorPalette() ColorPalette {
294 if pc.ColorPalette != nil {
295 return pc.ColorPalette
296 }
297 return AlternateColorPalette
298 }
299
300 // Box returns the chart bounds as a box.
301 func (pc PieChart) Box() Box {
302 dpr := pc.Background.Padding.GetRight(DefaultBackgroundPadding.Right)
303 dpb := pc.Background.Padding.GetBottom(DefaultBackgroundPadding.Bottom)
304
305 return Box{
306 Top: pc.Background.Padding.GetTop(DefaultBackgroundPadding.Top),
307 Left: pc.Background.Padding.GetLeft(DefaultBackgroundPadding.Left),
308 Right: pc.GetWidth() - dpr,
309 Bottom: pc.GetHeight() - dpb,
310 }
311 }