Back to godoc.org

Package histogram

v0.1.9
Latest Go to latest

The latest major version is .

Published: Dec 21, 2019 | License: Apache-2.0 | Module: github.com/calebcase/gomnia

Index

Variables

var (
	Format  string = "ascii"
	Variant string = "default"

	Width  float64 = 40
	Height float64 = 20
)
var Cmd = &cobra.Command{
	Use:   "histogram",
	Short: "plot a histogram",
	Long:  "" /* 151 byte string literal not displayed */,

	RunE: func(command *cobra.Command, args []string) (err error) {
		centroids := plotter.XYs{}
		scanner := bufio.NewScanner(os.Stdin)

		var x, y float64
		var xs, ys []float64
		ys = append(ys, 0)
		for scanner.Scan() {
			_, err = fmt.Sscanf(scanner.Text(), "%g %g", &x, &y)
			if err != nil {
				return
			}

			centroids = append(centroids, plotter.XY{
				X: x,
				Y: y,
			})

			xs = append(xs, x)
			ys = append(ys, y)
		}
		err = scanner.Err()
		if err != nil {
			return
		}

		var of *os.File

		if cmdPlot.OutputPath == "-" {
			of = os.Stdout
		} else {
			of, err = os.Create(cmdPlot.OutputPath)
			if err != nil {
				return
			}
		}

		flags := command.Flags()
		if flags.Changed("output") && !flags.Changed("format") {
			ext := filepath.Ext(cmdPlot.OutputPath)
			if ext != "" {
				Format = ext[1:]
			}
		}

		switch Format {
		case "ascii":
			switch Variant {
			case "default":
				fallthrough
			case "horizontal":
				w := tabwriter.NewWriter(of, 0, 0, 1, ' ', 0)

				for _, point := range centroids {
					fmt.Fprintf(w, "%g\t:\t%s %.0f\n", point.X, renderHBar(rescale(point.Y, floats.Min(ys), floats.Max(ys), 0, Width), true), point.Y)
				}

				w.Flush()
			case "vertical":
				vbars := []float64{}

				for _, y := range ys {
					vbars = append(vbars, 0, y, y, y)
				}
				vbars = append(vbars, 0, 0, 0, 0, 0)

				if flags.Changed("width") {
					fmt.Fprintln(of, asciigraph.Plot(vbars, asciigraph.Height(int(Height)), asciigraph.Width(int(Width))))
				} else {
					fmt.Fprintln(of, asciigraph.Plot(vbars, asciigraph.Height(int(Height))))
				}
			default:
				err = errors.New("invalid variant specified")
				return
			}
		default:
			var p *plot.Plot
			p, err = plot.New()
			if err != nil {
				return
			}

			p.Title.Text = "histogram"
			p.X.Label.Text = "x"
			p.Y.Label.Text = "count"

			var h *plotter.Histogram
			h, err = plotter.NewHistogram(centroids, len(centroids))
			if err != nil {
				return
			}
			p.Add(h)

			var w io.WriterTo
			w, err = p.WriterTo(vg.Length(Width)*vg.Centimeter, vg.Length(Height)*vg.Centimeter, Format)
			if err != nil {
				return
			}

			_, err = w.WriteTo(of)
			if err != nil {
				return
			}
		}

		return
	},
}
Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier