英文:
Gonum Plot Loop Through Slice
问题
我正在尝试使用循环添加多个图形,但是我似乎无法弄清楚如何放置这些线条。以下是我正在处理的代码:
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]),
//需要弄清楚如何循环遍历processes
)
if err != nil {
panic(err)
}
//将图形保存为PNG文件。
if err := p.Save(4*vg.Inch, 4*vg.Inch, "points.png"); err != nil {
panic(err)
}
}
我的getPoints函数如下所示:
```go
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
}
当我尝试在注释部分放置循环时,会出现错误。我知道这应该是相当简单的。也许在此之前需要一个循环来获取线条列表?
类似于
for i, process := range processes {
return "title", getPoints(process),
}
显然,我知道这不正确,但是我不确定该如何处理。
英文:
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.
答案1
得分: 0
我认为你想首先将你的数据提取到[]interface{}
中,然后调用AddLinePoints
函数。大致如下(我没有测试):
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...)
请注意,这是一个示例代码,具体实现可能需要根据你的需求进行调整。
英文:
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...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论