plot
plot copied to clipboard
plot: Can't add data labels to the barchart
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
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 Would you like to send a PR?