Skip to content

Commit

Permalink
Add thumbnailer for palette.Palette
Browse files Browse the repository at this point in the history
  • Loading branch information
ctessum committed Apr 29, 2017
1 parent d6e130c commit 107b1c9
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 1 deletion.
14 changes: 13 additions & 1 deletion plotter/heat_test.go
Expand Up @@ -5,6 +5,7 @@
package plotter

import (
"fmt"
"log"
"testing"

Expand Down Expand Up @@ -48,7 +49,8 @@ func ExampleHeatMap() {
5, 6, 7, 8,
9, 10, 11, 12,
})}
h := NewHeatMap(m, palette.Heat(12, 1))
plte := palette.Heat(12, 1)
h := NewHeatMap(m, plte)

p, err := plot.New()
if err != nil {
Expand All @@ -58,6 +60,16 @@ func ExampleHeatMap() {

p.Add(h)

// Create a legend.
rng := h.Max - h.Min
thumbs := PaletteThumbnailers(plte)
for i := len(thumbs) - 1; i >= 0; i-- {
t := thumbs[i]
fmin := float64(i) / float64(len(thumbs))
fmax := float64(i+1) / float64(len(thumbs))
p.Legend.Add(fmt.Sprintf("%.2g - %.2g", h.Min+fmin*rng, h.Min+fmax*rng), t)
}

p.X.Padding = 0
p.Y.Padding = 0
p.X.Max = 1.5
Expand Down
67 changes: 67 additions & 0 deletions plotter/palettethumbnailer.go
@@ -0,0 +1,67 @@
// Copyright ©2017 The gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package plotter

import (
"image/color"

"github.com/gonum/plot"
"github.com/gonum/plot/palette"
"github.com/gonum/plot/vg"
"github.com/gonum/plot/vg/draw"
)

// PaletteThumbnailers creates a group of objects that can be used to
// add legend entries for the colors in a color palette.
func PaletteThumbnailers(p palette.Palette) []plot.Thumbnailer {
colors := p.Colors()
thumbnailers := make([]plot.Thumbnailer, len(colors))
for i, c := range colors {
thumbnailers[i] = paletteThumbnailer{color: c}
}
return thumbnailers
}

// paletteThumbnailer implements the Thumbnailer interface
// for color palettes.
type paletteThumbnailer struct {
color color.Color
}

// Thumbnail fulfills the plot.Thumbnailer interface.
func (t paletteThumbnailer) Thumbnail(c *draw.Canvas) {
lineStyle := draw.LineStyle{
Color: color.Black,
Width: vg.Points(1),
Dashes: []vg.Length{},
DashOffs: 0,
}

// Here we draw the fill.
pts := []vg.Point{
{X: c.Min.X, Y: c.Min.Y},
{X: c.Min.X, Y: c.Max.Y},
{X: c.Max.X, Y: c.Max.Y},
{X: c.Max.X, Y: c.Min.Y},
}
poly := c.ClipPolygonY(pts)
c.FillPolygon(t.color, poly)

// Here we draw the upper border.
pts = []vg.Point{
{X: c.Min.X, Y: c.Max.Y},
{X: c.Max.X, Y: c.Max.Y},
}
outline := c.ClipLinesY(pts)
c.StrokeLines(lineStyle, outline...)

// Here we draw the lower border.
pts = []vg.Point{
{X: c.Min.X, Y: c.Min.Y},
{X: c.Max.X, Y: c.Min.Y},
}
outline = c.ClipLinesY(pts)
c.StrokeLines(lineStyle, outline...)
}

0 comments on commit 107b1c9

Please sign in to comment.