Skip to content
This repository has been archived by the owner on Aug 23, 2024. It is now read-only.

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

Open
tecnologer opened this issue Aug 4, 2024 · 0 comments
Open

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

tecnologer opened this issue Aug 4, 2024 · 0 comments

Comments

@tecnologer
Copy link

tecnologer commented Aug 4, 2024

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant