histogram

package
v0.1.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 7, 2021 License: Apache-2.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

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

	Width  float64 = 40
	Height float64 = 20
)
View Source
var Cmd = &cobra.Command{
	Use:   "histogram",
	Short: "plot a histogram",
	Long: `Plot a histogram.

Data should already be in histogram shape (x by count; see generate histogram
sub-command).

https://en.wikipedia.org/wiki/Histogram`,
	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
	},
}

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL