Created
November 26, 2019 18:58
-
-
Save cleuton/001b589cdd6afac12283ce862bbbbd47 to your computer and use it in GitHub Desktop.
Histogram using Golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Cleuton Sampaio | |
package main | |
import ( | |
"fmt" | |
"math" | |
"math/rand" | |
"github.com/emirpasic/gods/utils" | |
"gonum.org/v1/plot" | |
"gonum.org/v1/plot/plotter" | |
"gonum.org/v1/plot/plotutil" | |
"gonum.org/v1/plot/vg" | |
"github.com/emirpasic/gods/maps/treemap" | |
) | |
func randomArray(len int) []float64 { | |
a := make([]float64, len) | |
for i := 0; i <= len-1; i++ { | |
a[i] = math.Round(rand.Float64()*1000) / 100 | |
} | |
return a | |
} | |
func main() { | |
rand.Seed(42) | |
m := treemap.NewWith(utils.Float64Comparator) | |
m.Put(0.0, 0) | |
m.Put(2.0, 0) | |
m.Put(4.0, 0) | |
m.Put(6.0, 0) | |
m.Put(8.0, 0) | |
averages := randomArray(100) | |
for _, element := range averages { | |
key, value := m.Floor(element) | |
v := 1 + value.(int) | |
fmt.Println(" Element ", element, " Key ", key, " value ", value) | |
m.Put(key, v) | |
} | |
fmt.Println(m) | |
orig := m.Values() | |
floatV := []float64{} | |
for _, v := range orig { | |
floatV = append(floatV, float64(v.(int))) | |
} | |
groupA := plotter.Values(floatV) | |
p, err := plot.New() | |
if err != nil { | |
panic(err) | |
} | |
p.Title.Text = "Histogram" | |
p.Y.Label.Text = "Count" | |
w := vg.Points(20) | |
barsA, err := plotter.NewBarChart(groupA, w) | |
if err != nil { | |
panic(err) | |
} | |
barsA.LineStyle.Width = vg.Length(0) | |
barsA.Color = plotutil.Color(0) | |
barsA.Offset = -w | |
p.Add(barsA) | |
p.Legend.Top = true | |
p.NominalX("<=2", "<=4", "<=6", "<=8", ">8") | |
if err := p.Save(5*vg.Inch, 3*vg.Inch, "./histogram.png"); err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment