wcharczuk / go-chart

go chart is a basic charting library in go.
MIT License
3.99k stars 326 forks source link

How display the value over the dot in a linear chart? #228

Open tecnologer opened 2 months ago

tecnologer commented 2 months ago

Question

I am working with go-chart to create a linear chart and want to display values directly over the dots representing data points on the line. However, I'm unsure how to properly implement this, as my current attempts have not displayed the labels.

What I've Tried

Here's a snippet of my code that attempts to render text labels over the dots:

type TimeSeries struct {
    chart.TimeSeries
}

// Render renders the series to the chart.
func (ats *TimeSeries) Render(renderer chart.Renderer, canvasBox chart.Box, xRange, yRange chart.Range, defaultStyle chart.Style) {
    style := ats.Style.InheritFrom(defaultStyle)

    // Render the line and dots as usual
    ats.TimeSeries.Render(renderer, canvasBox, xRange, yRange, style)

    // Set font and color for text rendering
    renderer.SetFont(style.GetFont())
    renderer.SetFontColor(chart.ColorAlternateGreen) // Set a bright color for visibility

    // X is filled with time.Time values
    for index, date := range ats.XValues {
        // Convert time.Time to float64 for the x-axis
        xValue := xRange.Translate(chart.TimeToFloat64(date))
        yValue := yRange.Translate(ats.YValues[index])

        // Format the label text
        label := fmt.Sprintf("%.2f", ats.YValues[index])

        // Measure text size
        textDimensions := renderer.MeasureText(label)

        // Calculate text position to ensure visibility
        textX := canvasBox.Left + xValue - textDimensions.Width()/2
        textY := canvasBox.Top + yValue - textDimensions.Height() - 10 // Adjusted for visibility

        // Draw the text
        renderer.Text(label, textX, textY)
    }
}

Current result

It draws the lines and the dots but not the labels; see the example: 2024-08-04_stats


If you want to see all the code, see here.