-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.go
83 lines (73 loc) · 2.33 KB
/
graph.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
import (
"os"
"io"
"fmt"
"bytes"
"html/template"
"github.com/go-echarts/go-echarts/v2/opts"
"github.com/go-echarts/go-echarts/v2/types"
"github.com/go-echarts/go-echarts/v2/charts"
chartrender "github.com/go-echarts/go-echarts/v2/render"
)
/* code to embed echarts graphs in templates adapted from
* https://blog.cubieserver.de/2020/how-to-render-standalone-html-snippets-with-go-echarts/
* under https://creativecommons.org/licenses/by/4.0/ */
type embedRender struct {
c interface{}
before []func()
}
func NewEmbedRender(c interface{}, before ...func()) chartrender.Renderer {
return &embedRender{c: c, before: before}
}
func (r *embedRender) Render(w io.Writer) error {
data, err := os.ReadFile("html/graph.html")
baseTpl := string(data)
const tplName = "chart"
for _, fn := range r.before {
fn()
}
tpl := template.
Must(template.New(tplName). // must wraps a func returning a template, panics if err
Funcs(template.FuncMap{
"safeJS": func(s interface{}) template.JS {
return template.JS(fmt.Sprint(s)) // concatenates and casts to type JS
},
}).
Parse(baseTpl),
)
err = tpl.ExecuteTemplate(w, tplName, r.c)
return err
}
func renderGraph(counts map[string](map[string]int), p *Parameters, buf *bytes.Buffer) error {
barData := make(map[string]([]opts.BarData))
for _, section := range sections {
var barValues []opts.BarData
for _, year := range years {
count := counts[section][year] // zero if not in map
barValues = append(barValues, opts.BarData{Value: count})
}
barData[section] = barValues
}
// create a new bar instance
bar := charts.NewBar()
bar.Renderer = NewEmbedRender(bar, bar.Validate)
// set some global options like Title/Legend/ToolTip or anything else
bar.SetGlobalOptions(
charts.WithTitleOpts(opts.Title{
Title: p.searchTerm,
Subtitle: p.stockIndex,
}),
charts.WithLegendOpts(opts.Legend{Top: "bottom", Show: true}),
charts.WithInitializationOpts(opts.Initialization{Theme: types.ThemeWesteros}),
)
// Put data into instance
bar.SetXAxis(years).
AddSeries(sections[0], barData[sections[0]]).
AddSeries(sections[1], barData[sections[1]]).
SetSeriesOptions(charts.WithBarChartOpts(opts.BarChart{
Stack: "stackA",
}))
err := bar.Render(buf)
return err
}