Skip to content

Instantly share code, notes, and snippets.

@ajstarks
Created May 25, 2018 11:50
Show Gist options
  • Save ajstarks/8b1c24545264c20625073faa5e079a59 to your computer and use it in GitHub Desktop.
Save ajstarks/8b1c24545264c20625073faa5e079a59 to your computer and use it in GitHub Desktop.
Gophercises SVGo example refactor
package main
import (
"os"
"github.com/ajstarks/svgo"
)
func main() {
canvas := svg.New(os.Stdout)
data := []struct {
Month string
Usage int
}{
{"Jan", 171},
{"Feb", 180},
{"Mar", 100},
{"Apr", 87},
{"May", 65},
{"Jun", 40},
{"Jul", 32},
{"Aug", 55},
{"Sep", 0},
{"Oct", 0},
{"Nov", 0},
{"Dec", 0},
}
// tweak these to control the width and separation of the bars
barwidth := 50
offset := 10
width := len(data)*barwidth + offset
height := 300
threshold := 160
barcolor := canvas.RGB(77, 200, 232)
bottom := (height - 50)
max := 0
for _, item := range data {
if item.Usage > max {
max = item.Usage
}
}
canvas.Start(width, height)
canvas.Rect(0, 0, width, height, "fill:white")
canvas.Gstyle("font-size:14pt;fill:rgb(150, 150, 150);text-anchor:middle")
for i, val := range data {
barx := i*barwidth + offset
tx := barx + ((barwidth - offset) / 2)
percent := val.Usage * bottom / max
canvas.Rect(barx, bottom-percent, barwidth-offset, percent, barcolor)
canvas.Text(tx, height-24, val.Month)
}
canvas.Gend()
threshPercent := threshold * bottom / max
canvas.Line(0, height-threshPercent, width, height-threshPercent, "stroke: rgb(255,100,100); opacity: 0.8; stroke-width: 2px")
canvas.Rect(0, 0, width, height-threshPercent, "fill:rgb(255, 100, 100); opacity: 0.1")
canvas.Line(0, bottom, width, bottom, "stroke: rgb(150, 150, 150); stroke-width:2")
canvas.End()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment