Skip to content

plot: Can't add data labels to the barchart #475

Open

Description

@amidam

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

Activity

  1. ffhelicopter commented on Jun 6, 2019

    @ffhelicopter

    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)
    
    	}
    }
    
  2. kortschak commented on Jun 6, 2019

    @kortschak
    Member

    @ffhelicopter Would you like to send a PR?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions