使用的Go库
gonum.org/v1/plot
image/color
待绘图函数
直接使用三角函 s i n sin sin:
func f(x float64) float64 {
return math.Sin(x)
}
绘图过程
1 创建一个绘图
p := plot.New()
assert.NotNil(t, p)
p.Title.Text = "Function Image"
p.X.Label.Text = "X"
p.Y.Label.Text = "Y"
2 生成一些函数的点
points := make(plotter.XYZs, 100, 100)
for i := range points {
x := float64(i) / 10.0
y := f(x)
points[i].X = x
points[i].Y = y
}
3 将这些点连成线条
line, err := plotter.NewLine(points)
assert.Nil(t, err)
line.Color = color.RGBA{R: 255}
p.Add(line)
4 将绘图保存到图片
err = p.Save(4*vg.Inch, 4*vg.Inch, "func_image.png")
assert.Nil(t, err)
5 绘图效果
完整源码
函数定义
package funcimage
import "math"
func f(x float64) float64 {
return math.Sin(x)
}
画图像
package funcimage
import (
"github.com/stretchr/testify/assert"
"gonum.org/v1/plot"
"gonum.org/v1/plot/plotter"
"gonum.org/v1/plot/vg"
"image/color"
"testing"
)
func Test_func_image(t *testing.T) {
p := plot.New()
assert.NotNil(t, p)
p.Title.Text = "Function Image"
p.X.Label.Text = "X"
p.Y.Label.Text = "Y"
points := make(plotter.XYZs, 100, 100)
for i := range points {
x := float64(i) / 10.0
y := f(x)
points[i].X = x
points[i].Y = y
}
line, err := plotter.NewLine(points)
assert.Nil(t, err)
line.Color = color.RGBA{R: 255}
p.Add(line)
err = p.Save(4*vg.Inch, 4*vg.Inch, "func_image.png")
assert.Nil(t, err)
}