bar_chart.gno
1.16 Kb · 51 lines
1package charts
2
3import (
4 "strings"
5
6 "gno.land/p/nt/ufmt"
7)
8
9// GenerateBarChart creates an ASCII bar chart in markdown format
10// values: slice of float values to chart
11// labels: slice of labels for each bar
12// maxWidth: maximum width of bars in characters
13// title: chart title
14// Returns a markdown string representing the chart
15func GenerateBarChart(values []float64, labels []string, maxWidth int, title string) string {
16 if len(values) == 0 || len(labels) == 0 || len(values) != len(labels) {
17 return "invalid data for display"
18 }
19
20 if maxWidth <= 0 {
21 return "maxWidth must be greater than 0"
22 }
23
24 maxVal := findMaxValue(values)
25
26 maxLabelLength := 0
27 for _, label := range labels {
28 if len(label) > maxLabelLength {
29 maxLabelLength = len(label)
30 }
31 }
32
33 scale := float64(maxWidth) / maxVal
34
35 output := formatChartHeader(title)
36 output += "\n```\n"
37
38 for i, value := range values {
39 padding := strings.Repeat(" ", maxLabelLength-len(labels[i]))
40 output += labels[i] + padding + " "
41
42 barLength := int(value * scale)
43 output += strings.Repeat("█", barLength)
44
45 output += " " + ufmt.Sprintf("%.2f", value)
46 output += "\n"
47 }
48
49 output += "```\n"
50 return output
51}