How can I modify my golang main() func to create a cartesian x,y using the e-chart library. I've not found any example for this trivial case and the examples shown in the https://github.com/go-echarts/go-echarts contains x as categorical labels.
There is an example shown https://echarts.apache.org/examples/en/editor.html?c=line-in-cartesian-coordinate-system for plotting x,y for reference
option = {
xAxis: {},
yAxis: {},
series: [
{
data: [
[10, 40],
[50, 100],
[40, 20]
],
type: 'line'
}
]
};
func main() {
// Create a new line chart
line := charts.NewLine()
// Set chart title and options
line.SetGlobalOptions(
charts.WithTitleOpts(opts.Title{Title: "Circle in Cartesian Coordinates"}),
charts.WithTooltipOpts(opts.Tooltip{Trigger: "axis"}),
charts.WithLegendOpts(opts.Legend{Data: []string{"Circle"}}),
)
// Generate the circle data
radius := 10.0
numPoints := 100
xData, yData := generateCircleData(radius, numPoints)
// Add the circle data to the chart
//line.SetXAxis(xData).
// AddSeries("Circle", yData)
//line.Data.options.AddSeries.data
// Serve the chart as a web page
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
err := line.Render(w)
if err != nil {
log.Println("Error rendering chart:", err)
}
})
// Start the server
log.Println("Starting server on :8080")
http.ListenAndServe(":8080", nil)
}
I tried other examples shown in the e-chart repository but the x-labels for these examples were categorically 'strings'
A Scatter
chart is created using NewScatter()
. This works well for Cartesian coordinates where each (x, y)
is treated as a data point.
The x-axis and y-axis are set to numeric values (not categorical) using charts.WithXAxisOpts()
and charts.WithYAxisOpts()
.
package main
import (
"log"
"math"
"net/http"
"github.com/go-echarts/go-echarts/v2/charts"
"github.com/go-echarts/go-echarts/v2/opts"
)
func main() {
line := charts.NewScatter()
line.SetGlobalOptions(
charts.WithTitleOpts(opts.Title{Title: "Cartesian Coordinates Example"}),
charts.WithXAxisOpts(opts.XAxis{Type: "value", Name: "X-Axis"}),
charts.WithYAxisOpts(opts.YAxis{Type: "value", Name: "Y-Axis"}),
)
radius := 10.0
numPoints := 100
data := generateCircleData(radius, numPoints)
line.AddSeries("Circle", data)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
err := line.Render(w)
if err != nil {
log.Println("Error rendering chart:", err)
}
})
log.Println("Starting server at http://localhost:8081")
http.ListenAndServe(":8081", nil)
}
func generateCircleData(radius float64, numPoints int) []opts.ScatterData {
data := make([]opts.ScatterData, 0, numPoints)
for i := 0; i < numPoints; i++ {
theta := 2 * math.Pi * float64(i) / float64(numPoints) // Angle in radians
x := radius * math.Cos(theta)
y := radius * math.Sin(theta)
data = append(data, opts.ScatterData{Value: [2]float64{x, y}})
}
return data
}