Skip to content

Instantly share code, notes, and snippets.

@jtbonhomme
Created December 22, 2018 11:09
Show Gist options
  • Save jtbonhomme/f201dbaa3c055128c7308e9d3eece9f5 to your computer and use it in GitHub Desktop.
Save jtbonhomme/f201dbaa3c055128c7308e9d3eece9f5 to your computer and use it in GitHub Desktop.
Normal distribution generated data with color and x-axis legend
package main
import (
"log"
"net/http"
"time"
"math/rand"
chart "github.com/wcharczuk/go-chart"
"github.com/wcharczuk/go-chart/drawing"
)
const SAMPLES = 200
const SCALE = "24h"
func addData(ts *chart.TimeSeries, start time.Time, d time.Duration, samples int) {
t := start
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < samples; i++ {
ts.XValues = append(ts.XValues, t)
ts.YValues = append(ts.YValues, r.NormFloat64() + 10)
t = t.Add(d)
}
}
func drawChart(res http.ResponseWriter, req *http.Request) {
var graph *chart.Chart
var ts *chart.TimeSeries
ts = &chart.TimeSeries{
Style: chart.Style{
Show: true, //note; if we set ANY other pro$
StrokeColor: drawing.ColorBlue, // will supercede defaults
FillColor: drawing.ColorBlue.WithAlpha(64), // will supercede defaults
},
XValues: []time.Time{},
YValues: []float64{},
}
graph = &chart.Chart{
XAxis: chart.XAxis{
Style: chart.StyleShow(),
ValueFormatter: chart.TimeHourValueFormatter,
},
Series: []chart.Series{ts},
}
duration, _ := time.ParseDuration(SCALE)
end := time.Now()
start := end.Add(-duration)
addData(ts, start, duration/SAMPLES, SAMPLES)
if len(ts.XValues) == 0 {
http.Error(res, "no data (yet)", http.StatusBadRequest)
return
}
res.Header().Set("Content-Type", "image/png")
if err := graph.Render(chart.PNG, res); err != nil {
log.Printf("%v", err)
}
}
func main() {
http.HandleFunc("/", drawChart)
log.Printf("Open http://localhost:8080\n")
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment