Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 82 additions & 25 deletions legend.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
package plot

import (
"image/color"
"math"

xfont "golang.org/x/image/font"

"gonum.org/v1/plot/font"
"gonum.org/v1/plot/text"
"gonum.org/v1/plot/vg"
Expand All @@ -18,6 +21,10 @@ import (
// and a thumbnail, where the thumbnail shows a small
// sample of the display style of the corresponding data.
type Legend struct {
// BackgroundColor is the color behind the legend entries.
// A nil color leaves the background transparent.
BackgroundColor color.Color

// TextStyle is the style given to the legend
// entry texts.
TextStyle text.Style
Expand Down Expand Up @@ -94,6 +101,21 @@ func newLegend(hdlr text.Handler) Legend {

// Draw draws the legend to the given draw.Canvas.
func (l *Legend) Draw(c draw.Canvas) {
if l.BackgroundColor != nil && len(l.entries) != 0 {
r := l.Rectangle(c)
c.SetColor(l.BackgroundColor)
c.Fill(r.Path())
}
l.layout(c, func(sty text.Style, pt vg.Point, icon *draw.Canvas, e legendEntry) {
for _, t := range e.thumbs {
t.Thumbnail(icon)
}
c.FillText(sty, pt, e.text)
})
}

// layout visits the entries at the positions used to draw them.
func (l *Legend) layout(c draw.Canvas, visit func(text.Style, vg.Point, *draw.Canvas, legendEntry)) {
iconx := c.Min.X
sty := l.TextStyle
em := sty.Rectangle(" ")
Expand Down Expand Up @@ -129,43 +151,78 @@ func (l *Legend) Draw(c draw.Canvas) {
yoff += descent

for _, e := range l.entries {
for _, t := range e.thumbs {
t.Thumbnail(icon)
}
yoffs := (enth - descent - sty.Rectangle(e.text).Max.Y) / 2
yoffs += yoff
c.FillText(sty, vg.Point{X: textx, Y: icon.Min.Y + yoffs}, e.text)
visit(sty, vg.Point{X: textx, Y: icon.Min.Y + yoffs}, icon, e)
icon.Min.Y -= enth + l.Padding
icon.Max.Y -= enth + l.Padding
}
}

// Rectangle returns the extent of the Legend.
func (l *Legend) Rectangle(c draw.Canvas) vg.Rectangle {
var width, height vg.Length
sty := l.TextStyle
entryHeight := l.entryHeight()
for i, e := range l.entries {
width = vg.Length(math.Max(float64(width), float64(l.ThumbnailWidth+sty.Rectangle(" "+e.text).Max.X)))
height += entryHeight
if i != 0 {
height += l.Padding
r := vg.Rectangle{
Min: vg.Point{X: vg.Length(math.Inf(1)), Y: vg.Length(math.Inf(1))},
Max: vg.Point{X: vg.Length(math.Inf(-1)), Y: vg.Length(math.Inf(-1))},
}
include := func(box vg.Rectangle) {
r.Min.X, r.Min.Y = min(r.Min.X, box.Min.X), min(r.Min.Y, box.Min.Y)
r.Max.X, r.Max.Y = max(r.Max.X, box.Max.X), max(r.Max.Y, box.Max.Y)
}
l.layout(c, func(sty text.Style, pt vg.Point, icon *draw.Canvas, e legendEntry) {
include(icon.Rectangle)
include(legendTextRectangle(sty, e.text).Add(pt))
})
if len(l.entries) == 0 {
p := c.Min
if !l.Left {
p.X = c.Max.X
}
if l.Top {
p.Y = c.Max.Y
}
p = p.Add(vg.Point{X: l.XOffs, Y: l.YOffs})
return vg.Rectangle{Min: p, Max: p}
}
return r
}

// legendTextRectangle includes glyph overhangs and the line positions used by
// the plain text handler, as well as the handler's layout bounds.
func legendTextRectangle(sty text.Style, txt string) vg.Rectangle {
r := sty.Rectangle(txt)
switch sty.Handler.(type) {
case text.Plain, *text.Plain:
default:
return r
}
var r vg.Rectangle
if l.Left {
r.Max.X = c.Max.X
r.Min.X = c.Max.X - width
} else {
r.Max.X = c.Min.X + width
r.Min.X = c.Min.X
if sty.Font.Size <= 0 {
return r
}
if l.Top {
r.Max.Y = c.Max.Y
r.Min.Y = c.Max.Y - height
} else {
r.Max.Y = c.Min.Y + height
r.Min.Y = c.Min.Y
face := sty.Handler.Cache().Lookup(sty.Font, sty.Font.Size)
// Measure at the font's design resolution to avoid pixel rounding.
em := float64(face.Face.UnitsPerEm())
glyphs := face.FontFace(72 * em / face.Font.Size.Points())
defer glyphs.Close()
scale := face.Font.Size / vg.Length(64*em)
lines := sty.Handler.Lines(txt)
y := sty.Height(txt)*vg.Length(sty.YAlign) - face.Extents().Ascent
sin, cos := math.Sincos(sty.Rotation)
for i, line := range lines {
if line == "" {
continue
}
bounds, _ := xfont.BoundString(glyphs, line)
xoff := vg.Length(sty.XAlign) * face.Width(line)
yoff := y + vg.Length(len(lines)-i)*sty.Font.Size
for _, x := range []vg.Length{vg.Length(bounds.Min.X) * scale, vg.Length(bounds.Max.X) * scale} {
for _, y := range []vg.Length{-vg.Length(bounds.Max.Y) * scale, -vg.Length(bounds.Min.Y) * scale} {
x, y := x+xoff, y+yoff
p := vg.Point{X: x*vg.Length(cos) - y*vg.Length(sin), Y: x*vg.Length(sin) + y*vg.Length(cos)}
r.Min.X, r.Min.Y = min(r.Min.X, p.X), min(r.Min.Y, p.Y)
r.Max.X, r.Max.Y = max(r.Max.X, p.X), max(r.Max.Y, p.Y)
}
}
}
return r
}
Expand Down
19 changes: 19 additions & 0 deletions legend_example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"os"

"gonum.org/v1/plot"
"gonum.org/v1/plot/plotter"
"gonum.org/v1/plot/vg"
"gonum.org/v1/plot/vg/draw"
"gonum.org/v1/plot/vg/vgimg"
Expand All @@ -18,6 +19,24 @@ type exampleThumbnailer struct {
color.Color
}

// This example gives an overlaid legend an opaque background.
func ExampleLegend_background() {
p := plot.New()
line, err := plotter.NewLine(plotter.XYs{{X: 0, Y: 0}, {X: 1, Y: 1}})
if err != nil {
panic(err)
}
p.Add(line)
p.Legend.Add("data", line)
p.Legend.Top = true
p.Legend.BackgroundColor = color.NRGBA{R: 230, G: 240, B: 250, A: 255}
p.Legend.XOffs = -vg.Points(4)
p.Legend.YOffs = -vg.Points(4)
if err := p.Save(vg.Points(180), vg.Points(120), "testdata/legend_background.png"); err != nil {
panic(err)
}
}

// Thumbnail fulfills the plot.Thumbnailer interface.
func (et exampleThumbnailer) Thumbnail(c *draw.Canvas) {
pts := []vg.Point{
Expand Down
177 changes: 177 additions & 0 deletions legend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,188 @@
package plot_test

import (
"image/color"
"math"
"reflect"
"testing"

xfont "golang.org/x/image/font"
"gonum.org/v1/plot"
"gonum.org/v1/plot/cmpimg"
"gonum.org/v1/plot/text"
"gonum.org/v1/plot/vg"
"gonum.org/v1/plot/vg/draw"
"gonum.org/v1/plot/vg/recorder"
)

func TestLegend_standalone(t *testing.T) {
cmpimg.CheckPlot(ExampleLegend_standalone, t, "legend_standalone.png")
}

func TestLegend_background(t *testing.T) {
cmpimg.CheckPlot(ExampleLegend_background, t, "legend_background.png")
}

func TestLegendBackground(t *testing.T) {
for _, left := range []bool{false, true} {
for _, top := range []bool{false, true} {
var canvas recorder.Canvas
c := draw.Canvas{Canvas: &canvas, Rectangle: vg.Rectangle{Min: vg.Point{X: 10, Y: 20}, Max: vg.Point{X: 210, Y: 120}}}
l := plot.NewLegend()
l.Add("first")
l.Add("second")
l.Left, l.Top = left, top
l.XOffs, l.YOffs = 3, 4
l.BackgroundColor = color.NRGBA{R: 230, G: 240, B: 250, A: 255}
l.Draw(c)
if len(canvas.Actions) < 2 {
t.Fatalf("no background drawn: %v", canvas.Actions)
}
clr, ok := canvas.Actions[0].(*recorder.SetColor)
if !ok || clr.Color != l.BackgroundColor {
t.Fatalf("first action = %v, want background color", canvas.Actions[0])
}
fill, ok := canvas.Actions[1].(*recorder.Fill)
if !ok {
t.Fatalf("second action = %v, want background fill", canvas.Actions[1])
}
r := l.Rectangle(c)
if !reflect.DeepEqual(fill.Path, r.Path()) {
t.Errorf("left=%t top=%t: background %v does not match legend rectangle %v", left, top, fill.Path, r)
}
if left && r.Min.X != c.Min.X+l.XOffs || !left && r.Max.X != c.Max.X+l.XOffs {
t.Errorf("left=%t: legend rectangle has wrong horizontal anchor: %v", left, r)
}
}
}
}

type legendBoundsThumbnail struct{ bounds *[]vg.Rectangle }

func (t legendBoundsThumbnail) Thumbnail(c *draw.Canvas) {
*t.bounds = append(*t.bounds, c.Rectangle)
}

func TestLegendBackgroundBounds(t *testing.T) {
for _, left := range []bool{false, true} {
for _, top := range []bool{false, true} {
for _, yposition := range []float64{draw.PosBottom, draw.PosCenter, draw.PosTop} {
for _, yalign := range []text.YAlignment{text.YBottom, text.YCenter, text.YTop} {
for _, rotation := range []float64{0, math.Pi / 6} {
var canvas recorder.Canvas
c := draw.Canvas{Canvas: &canvas, Rectangle: vg.Rectangle{Min: vg.Point{X: 10, Y: 20}, Max: vg.Point{X: 210, Y: 120}}}
l := plot.NewLegend()
l.Left, l.Top = left, top
l.XOffs, l.YOffs = 3, -4
l.YPosition = yposition
l.TextStyle.YAlign = yalign
l.TextStyle.Rotation = rotation
l.TextStyle.Font.Style = xfont.StyleItalic
l.Padding = vg.Points(2)
l.BackgroundColor = color.White
var icons []vg.Rectangle
thumb := legendBoundsThumbnail{bounds: &icons}
l.Add("Ågyp", thumb)
l.Add("first\n\nsecond", thumb)
l.Draw(c)
r := l.Rectangle(c)
check := func(p vg.Point) {
t.Helper()
const tol vg.Length = 1.0 / 64
if p.X < r.Min.X-tol || p.X > r.Max.X+tol || p.Y < r.Min.Y-tol || p.Y > r.Max.Y+tol {
t.Fatalf("left=%t top=%t yposition=%g yalign=%g rotation=%g: point %v outside background %v", left, top, yposition, yalign, rotation, p, r)
}
}
for _, icon := range icons {
check(icon.Min)
check(icon.Max)
}
var angle float64
var stack []float64
for _, action := range canvas.Actions {
switch a := action.(type) {
case *recorder.Push:
stack = append(stack, angle)
case *recorder.Pop:
angle, stack = stack[len(stack)-1], stack[:len(stack)-1]
case *recorder.Rotate:
angle += a.Angle
case *recorder.FillString:
if a.String == "" {
continue
}
fnt := l.TextStyle.Handler.Cache().Lookup(a.Font, a.Size)
face := fnt.FontFace(72)
bounds, _ := xfont.BoundString(face, a.String)
face.Close()
for _, x := range []int32{int32(bounds.Min.X), int32(bounds.Max.X)} {
for _, y := range []int32{int32(bounds.Min.Y), int32(bounds.Max.Y)} {
p := a.Point.Add(vg.Point{X: vg.Points(float64(x) / 64), Y: -vg.Points(float64(y) / 64)})
sin, cos := math.Sincos(angle)
check(vg.Point{X: p.X*vg.Length(cos) - p.Y*vg.Length(sin), Y: p.X*vg.Length(sin) + p.Y*vg.Length(cos)})
}
}
}
}
}
}
}
}
}
}

func TestLegendNoBackground(t *testing.T) {
for _, empty := range []bool{false, true} {
var canvas recorder.Canvas
c := draw.Canvas{Canvas: &canvas, Rectangle: vg.Rectangle{Max: vg.Point{X: 100, Y: 100}}}
l := plot.NewLegend()
if empty {
l.BackgroundColor = color.White
} else {
l.Add("entry")
}
l.Draw(c)
for _, action := range canvas.Actions {
if _, ok := action.(*recorder.Fill); ok {
t.Errorf("unexpected background fill for empty=%t", empty)
}
}
}
}

func TestLegendBackgroundZeroFont(t *testing.T) {
var canvas recorder.Canvas
c := draw.Canvas{Canvas: &canvas, Rectangle: vg.Rectangle{Max: vg.Point{X: 100, Y: 100}}}
l := plot.NewLegend()
l.TextStyle.Font.Size = 0
l.BackgroundColor = color.White
l.Add("entry")
l.Draw(c)
r := l.Rectangle(c)
for _, v := range []vg.Length{r.Min.X, r.Min.Y, r.Max.X, r.Max.Y} {
if math.IsNaN(float64(v)) || math.IsInf(float64(v), 0) {
t.Fatalf("non-finite zero-font legend bounds: %v", r)
}
}
}

func TestLegendRectangleEmpty(t *testing.T) {
c := draw.Canvas{Rectangle: vg.Rectangle{Min: vg.Point{X: 10, Y: 20}, Max: vg.Point{X: 210, Y: 120}}}
for _, left := range []bool{false, true} {
for _, top := range []bool{false, true} {
l := plot.NewLegend()
l.Left, l.Top = left, top
l.XOffs, l.YOffs = 3, -4
want := vg.Point{X: 213, Y: 16}
if left {
want.X = 13
}
if top {
want.Y = 116
}
if got := l.Rectangle(c); got.Min != want || got.Max != want {
t.Errorf("left=%t top=%t: empty legend bounds=%v, want point %v", left, top, got, want)
}
}
}
}
Binary file added testdata/legend_background_golden.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified testdata/legend_standalone_golden.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.