plot icon indicating copy to clipboard operation
plot copied to clipboard

plot: Can't add data labels to the barchart

Open amidam opened this issue 5 years ago • 2 comments

What are you trying to do?

I am trying to add data labels(show the value of each bar on top of it) to a bar chart.

What did you expect to happen?

A field in the BarChart struct which can set it to show the data labels or not and even where to put them.

What actually happened?

Right now there is no field in the BarChart struct

What version of Go and Gonum/plot are you using?

Go: 1.10.3 Gonum: 5f3c436

amidam avatar Oct 14 '18 14:10 amidam

modify plotter/barchart.go

// Plot implements the plot.Plotter interface.
func (b *BarChart) Plot(c draw.Canvas, plt *plot.Plot) {
	trCat, trVal := plt.Transforms(&c)
	if b.Horizontal {
		trCat, trVal = trVal, trCat
	}

	for i, ht := range b.Values {
		catVal := b.XMin + float64(i)
		catMin := trCat(float64(catVal))
		if !b.Horizontal {
			if !c.ContainsX(catMin) {
				continue
			}
		} else {
			if !c.ContainsY(catMin) {
				continue
			}
		}
		catMin = catMin - b.Width/2 + b.Offset
		catMax := catMin + b.Width
		bottom := b.stackedOn.BarHeight(i)
		valMin := trVal(bottom)
		valMax := trVal(bottom + ht)

		// value point
		topx := catMin
		topy := valMax

		var pts []vg.Point
		var poly []vg.Point
		if !b.Horizontal {
			pts = []vg.Point{
				{catMin, valMin},
				{catMin, valMax},
				{catMax, valMax},
				{catMax, valMin},
			}
			poly = c.ClipPolygonY(pts)
		} else {
			pts = []vg.Point{
				{valMin, catMin},
				{valMin, catMax},
				{valMax, catMax},
				{valMax, catMin},
			}
			poly = c.ClipPolygonX(pts)

			topx = valMax
			topy = catMin
		}
		c.FillPolygon(b.Color, poly)

		var outline [][]vg.Point
		if !b.Horizontal {
			pts = append(pts, vg.Point{X: catMin, Y: valMin})
			outline = c.ClipLinesY(pts)
		} else {
			pts = append(pts, vg.Point{X: valMin, Y: catMin})
			outline = c.ClipLinesX(pts)
		}
		c.StrokeLines(b.LineStyle, outline...)
		// show the value of each bar on top of it
		strvalue := fmt.Sprintln(ht)
		ft, _ := vg.MakeFont(plot.DefaultFont, 10)
		c.FillText(draw.TextStyle{Color: color.Black, Font: ft}, vg.Point{X: topx, Y: topy}, strvalue)

	}
}

ffhelicopter avatar Jun 06 '19 16:06 ffhelicopter

@ffhelicopter Would you like to send a PR?

kortschak avatar Jun 06 '19 21:06 kortschak