简体   繁体   中英

Gonum Plot Loop Through Slice

I'm trying to add multiple plots by using a loop, but I can't seem to figure out how to put the lines in. Here is the code I'm working on:

func plot_stochastic_processes(processes [][]float64, title string) {
    p, err := plot.New()
    if err != nil {
        panic(err)
    }

    p.Title.Text = title
    p.X.Label.Text = "X"
    p.Y.Label.Text = "Y"

    err = plotutil.AddLinePoints(p,
        "Test", getPoints(processes[1]),
        //Need to figure out how to loop through processes
    )
    if err != nil {
        panic(err)
    }

    // Save the plot to a PNG file.
    if err := p.Save(4*vg.Inch, 4*vg.Inch, "points.png"); err != nil {
        panic(err)
    }
}

My getPoints function looks like this:

func getPoints(line []float64) plotter.XYs {
    pts := make(plotter.XYs, len(line))
    for j, k := range line {
        pts[j].X = float64(j)
        pts[j].Y = k
    }
    return pts
}

I get an error when trying to put a loop where the commented section is. I know this should be fairly straightforward. Perhaps a loop prior to this to get the list of lines?

Something like

for i, process := range processes {
    return "title", getPoints(process),
}

Obviously I know that isn't correct, but not I'm not sure how to go about it.

I think you want to first extract your data into a []interface{} , and then call into AddLinePoints. Roughly (I didn't test):

lines := make([]interface{},0)
for i, v := range processes { 
    lines = append(lines, "Title" + strconv.Itoa(i))
    lines = append(lines, getPoints(v))
}
plotutil.AddLinePoints(p, lines...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM