Base plotting library for stock plotters

This library does not use any other libraries.
xxxxxxxxxx
122
 
1
###############################################################################
2
#                                                                             #
3
# Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/           #
4
# Contact: beat.support@idiap.ch                                              #
5
#                                                                             #
6
# This file is part of the beat.examples module of the BEAT platform.         #
7
#                                                                             #
8
# Commercial License Usage                                                    #
9
# Licensees holding valid commercial BEAT licenses may use this file in       #
10
# accordance with the terms contained in a written agreement between you      #
11
# and Idiap. For further information contact tto@idiap.ch                     #
12
#                                                                             #
13
# Alternatively, this file may be used under the terms of the GNU Affero      #
14
# Public License version 3 as published by the Free Software and appearing    #
15
# in the file LICENSE.AGPL included in the packaging of this file.            #
16
# The BEAT platform is distributed in the hope that it will be useful, but    #
17
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY  #
18
# or FITNESS FOR A PARTICULAR PURPOSE.                                        #
19
#                                                                             #
20
# You should have received a copy of the GNU Affero Public License along      #
21
# with the BEAT platform. If not, see http://www.gnu.org/licenses/.           #
22
#                                                                             #
23
###############################################################################
24
25
class Plotter(object):
26
27
28
    def setup(self, parameters):
29
        """Sets up basic parameters taking into consideration user input
30
31
        You must declare all entries you want to control from your plotter, at
32
        your plotter declaration.
33
34
        """
35
36
        self.xlabel = parameters.get('xlabel', 'X')
37
        self.xaxis_multiplier = parameters.get('xaxis_multiplier', 1.0)
38
        self.xaxis_log = parameters.get('xaxis_log', False)
39
        self.ylabel = parameters.get('ylabel', 'Y')
40
        self.yaxis_multiplier = parameters.get('yaxis_multiplier', 1.0)
41
        self.yaxis_log = parameters.get('yaxis_log', False)
42
        self.title  = parameters.get('title', 'Plot')
43
        self.label = parameters.get('legend', '').split('&')
44
        self.label = [k for k in self.label if k]
45
        self.grid = parameters.get('grid', False)
46
        self.content_type = parameters.get('content_type', 'image/png')
47
        self.dpi = parameters.get('dpi', 60)
48
        self.width = parameters.get('width', 400)
49
        self.height = parameters.get('height', 300)
50
51
52
    def prepare_canvas(self):
53
        """Prepares the figure canvas and the axis for plotting
54
55
        Returns:
56
57
          fig (matplotlib.pyplot.Figure): The figure canvas to draw on
58
          ax (matplotlib.pyplot.axes): The axis installed on the figure in
59
            which we will plot
60
61
        """
62
63
        # Creates the image to return
64
        from matplotlib.figure import Figure
65
        fig = Figure(
66
                frameon=False,
67
                figsize=(
68
                  float(self.width)/self.dpi,
69
                  float(self.height)/self.dpi,
70
                  ),
71
                dpi=self.dpi,
72
                tight_layout=True,
73
                )
74
        ax = fig.add_subplot(111)
75
76
        return fig, ax
77
78
79
    def apply_parameters(self, ax):
80
        """Applies all base parameters to the axis"""
81
82
        # Sets plot attributes
83
        ax.set_xlabel(self.xlabel)
84
        ax.set_ylabel(self.ylabel)
85
        ax.set_title(self.title)
86
        ax.grid(self.grid)
87
        if self.xaxis_log: ax.set_xscale('log')
88
        if self.yaxis_log: ax.set_yscale('log')
89
        if any(self.label): ax.legend()
90
91
92
    def encode_figure(self, fig):
93
        """Processes the figure and returns the image to be exported
94
95
        Returns:
96
97
          img (str): A binary string containing the image, with the type
98
            defined by the user
99
100
        """
101
102
        # Returns the image
103
        import six
104
        if six.PY2:
105
            output = six.StringIO()
106
        else:
107
            output = six.BytesIO()
108
109
        if self.content_type in ('image/png', 'image/jpeg'):
110
            from matplotlib.backends.backend_agg import FigureCanvasAgg
111
            canvas = FigureCanvasAgg(fig)
112
            if self.content_type.endswith('png'):
113
                canvas.print_png(output)
114
            else:
115
                canvas.print_jpg(output)
116
        else:
117
            from matplotlib.backends.backend_pdf import FigureCanvasPdf
118
            canvas = FigureCanvasPdf(fig)
119
            canvas.print_figure(output)
120
121
        return output.getvalue()
122

The code for this algorithm in Python
The ruler at 80 columns indicate suggested POSIX line breaks (for readability).
The editor will automatically enlarge to accomodate the entirety of your input
Use keyboard shortcuts for search/replace and faster editing. For example, use Ctrl-F (PC) or Cmd-F (Mac) to search through this box

Base plotting library containing common code for executing plots.

Usage

You must include this library so that your plotter can become an inherited type of the Plotter declared here:

class Plotter(baselib.Plotter):

  def __init__(self):

    super(Plotter, self).__init__()


  def setup(self, parameters):

    super(Plotter, self).setup(parameters)

    # setup other parameters, fix things


  def process(self, inputs):

    fig, ax = super(Plotter, self).prepare_canvas()

    # write here your plotting code

    super(Plotter, self).apply_parameters(ax)

    # you may override here plotting parameters applied by the base class

    return super(Plotter, self).encode_figure(fig)

Your plotter must then be declared as follows (so that all parameters are taken into account):

{
  "dataformat": "plot/<format>/1",
  "language": "python",
  "uses": {
    "baselib": "plot/baselib/1",
  },
  "description": "Whatever it should be",
  "multiple": true,
  "parameters": {
    "xlabel": {
      "default": "X",
      "type": "string",
      "description": "The label of the X-axis (horizontal)"
    },
    "ylabel": {
      "default": "Y",
      "type": "string",
      "description": "The label of the Y-axis (vertical)"
    },
    "title": {
      "default": "Scatter plot",
      "type": "string",
      "description": "The title for this plot"
    },
    "xaxis_multiplier": {
      "default": "1.0",
      "type": "float64",
      "description": "The multiplication factor for the X-axis (horizontal)"
    },
    "yaxis_multiplier": {
      "default": "1.0",
      "type": "float64",
      "description": "The multiplication factor for the Y-axis (vertical)"
    },
    "legend": {
      "default": "",
      "type": "string",
      "description": "Short description of the data, to be added to the plot"
    },
    "grid": {
      "default": false,
      "type": "bool",
      "description": "If we should draw grid lines or not for the plot"
    },
    "xaxis_log": {
      "default": false,
      "type": "bool",
      "description": "If X-axis (horizontal) should be in log-scale"
    },
    "yaxis_log": {
      "default": false,
      "type": "bool",
      "description": "If Y-axis (vertical) should be in log-scale"
    },
    "dpi": {
      "default": 60,
      "type": "uint16",
      "description": "Dots-per-inch in raster image formats"
    },
    "width": {
      "default": 400,
      "type": "uint16",
      "description": "Width of the resulting image in pixels"
    },
    "height": {
      "default": 300,
      "type": "uint16",
      "description": "Height of the resulting image in pixels"
    },
    "content_type": {
      "default": "image/png",
      "description": "The type of image returned",
      "type": "string",
      "choice": [
        "image/png",
        "image/jpeg",
        "application/pdf"
      ]
    }
  }
}
No referrer objects found.
Created with Raphaël 2.1.2[compare]plot/baselib/12015May4
No referrer algorithms found.
Terms of Service | Contact Information | BEAT platform version 2.2.1b0 | © Idiap Research Institute - 2013-2025