# mmplot
Plot a function.

## Synopsis

fig = mmplot( plotitems = [], options = [], outfig = -1, filename = None )

Implemented in Python.

### Input

plotitems | List of plotitems. Default: `[]`
options | List of options. Default: `[]`
outfig | Integer. Figure number. 0 creates a new figure. Default: `-1`
filename | String. Name of the PNG output file. Default: `None`

### Output

fig | Figure number.

## Description

mmplot plots a 2D function `y=f(x)` with the help of the Gnuplot package. mmplot may take four arguments.

- `plotitems` argument is a list of plotitems: `[plotitem_1, plotitem_2, ...]` , where each plotitem is a list containing the `x` axis, the `y` axis, the plot `style` (Gnuplot styles) and the function `title` . A plotitem looks like `"[x, y, style, title]"` , where `x` and `y` are Numeric arrays, `style` and `title` are strings. Parameters `y` , `style` and `title` are optionals. If `y` is not specified, `"Numeric.range(x) vs. x"` will be plotted. If `style` is not defined or is `None` , mmplot uses the global style, if it has been defined in `options` , or 'lines' style, when there is no global style. `plotitems` argument finally looks like `"[[x1, y1, 'a style', 'a title'], [x2], [x3, y3], [x4, y4, None, 'a title']"` .
- `options` argument is a list of option tuples: `[[option1, value1], [option2, value2], ...]` Available options are:
  - `'grid'` , adds a grid.
  - `'title'` , adds a global title to the graph.
  - `'xlabel'` , adds a label for X axis.
  - `'ylabel'` , adds a label for Y axis.
  - `'style'` , selects a global plot style. Accepts any Gnuplot style requiring no additional information. Gnuplot styles are: `lines`, `points`, `linespoints`, `impulses`, `dots`, `steps`, `fsteps`, `histeps`, `errorbars`, `xerrorbars`, `yerrorbars`, `xyerrorbars`, `errorlines`, `xerrorlines`, `yerrorlines`, `xyerrorlines`, `boxes`, `boxerrorbars`, `boxxyerrorbars`, `financebars`, `candlesticks` or `vector`. See Gnuplot help for these styles.
  - `'replot'` , treat plotitems as additional plotitems to be plotted alongside the existing graph. If replot is not specified, the graph will be cleared before the plot.
- `outfig` argument is the figure number to be plot. A list of figures is kept in global variable `__figs__` which is not supposed to be modified by the user. `__figs__[0]` stores the number of the current figure (last figure accessed by mmplot ). Each `__figs__[i]` is a Gnuplot pointer for figure `i` , `i>0` . If figure `outfig` already exists, data will be plotted in figure `outfig` and `outfig` is returned. If figure `outfig` does not exist, nothing is done and `0` is returned. If `outfig == 0` , data will be plotted in a new figure and the new figure number is returned. If `outfig` is not specified, data will be plotted in the current figure, if it already exists, or in a new figure, otherwise. The new figure number is then returned.
- `filename` argument is the name of the PNG output file.

There are also two special uses of mmplot . When mmplot is called with no args, the current figure is replotted and its number is returned. If there is no current figure, nothing is done and 0 is returned. mmplot ('reset') clears the figures table.

## Examples

    >>> import Numeric

    >>> #

    >>> x = Numeric.arange(0, 2*Numeric.pi, 0.1)

    >>> mmplot([[x]])

    >>> y1 = Numeric.sin(x)

    >>> y2 = Numeric.cos(x)

    >>> opts = [['title', 'Example Plot'],\
            ['grid'],\
            ['style', 'linespoints'],\
            ['xlabel', '"X values"'],\
            ['ylabel', '"Y Values"']]

    >>> y1_plt = [x, y1, None,    'sin(X)']

    >>> y2_plt = [x, y2, 'lines', 'cos(X)']

    >>> #

    >>> # plotting two graphs using one step

    >>> fig1 = mmplot([y1_plt, y2_plt], opts, 0)

    >>> #

    >>> # plotting the same graphs using two steps

    >>> fig2 = mmplot([y1_plt], opts, 0)

    >>> fig2 = mmplot([y2_plt], opts, fig2)

    >>> #

    >>> # first function has been lost, lets recover it

    >>> opts.append(['replot'])

    >>> fig2 = mmplot([y1_plt], opts, fig2)

[[x]] | [y1_plt, y2_plt], opts, 0 |

[y1_plt], opts, 0 | [y2_plt], opts, fig2 |

[y1_plt], opts, fig2 |

## Source Code

    def mmplot(plotitems=[], options=[], outfig=-1, filename=None):
        import Gnuplot
        import Numeric
        newfig = 0
        if (plotitems == 'reset'):
            __figs__[0] = None
            __figs__[1:] = []
            return 0
        if len(plotitems) == 0:
            # no plotitems specified: replot current figure
            if __figs__[0]:
                outfig = __figs__[0]
                g = __figs__[outfig]
                g.replot()
                return outfig
            else:
                #assert 0, "mmplot error: There is no current figure\n"
                print "mmplot error: There is no current figure\n"
                return 0
        # figure to be plotted
        if ((outfig < 0) and __figs__[0]):
            # current figure
            outfig = __figs__[0]
        elif ( (outfig == 0) or ( (outfig == -1) and not __figs__[0] )  ):
            # new figure
            newfig = 1
            outfig = len(__figs__)
        elif outfig >= len(__figs__):
            #assert 0, 'mmplot error: Figure ' + str(outfig) + 'does not exist\n'
            print 'mmplot error: Figure ' + str(outfig) + 'does not exist\n'
            return 0
        #current figure
        __figs__[0] = outfig
        # Gnuplot pointer
        if newfig:
            if len(__figs__) > 20:
                print '''mmplot error: could not create figure. Too many PlotItems in memory (20). Use
                         mmplot('reset') to clear table'''
                return 0
            g = Gnuplot.Gnuplot()
            __figs__.append(g)
        else:
            g = __figs__[outfig]
        # options
        try:
            options.remove(['replot'])
        except:
            g.reset()
        try:
            #default style
            g('set data style lines')
            for option in options:
                if option[0] == 'grid':
                    g('set grid')
                elif option[0] == 'title':
                    g('set title "' + option[1] + '"')
                elif option[0] == 'xlabel':
                    g('set xlabel ' + option[1])
                elif option[0] == 'ylabel':
                    g('set ylabel ' + option[1])
                elif option[0] == 'style':
                    g('set data style ' + option[1])
                else:
                    print "mmplot warning: Unknown option: " + option[0]
        except:
            print "mmplot warning: Bad usage in options! Using default values. Please, use help.\n"
        # Plot items: item[0]=x, item[1]=y, item[2]=style
        for item in plotitems:
            try:
                title = None
                style = None
                x = Numeric.ravel(item[0])
                if len(item) > 1:
                    # y axis specified
                    y = Numeric.ravel(item[1])
                    if len(item) > 2:
                        # style specified
                        style = item[2]
                        if len(item) > 3:
                            title = item[3]
                else:
                    # no y axis specified
                    y = x
                    x = Numeric.arange(len(y))
                g.replot(Gnuplot.Data(x, y, title=title, with=style))
            except:
                g.reset()
                if newfig:
                    __figs__.pop()
                #assert 0, "mmplot error: Bad usage in plotitems! Impossible to plot graph. Please, use help.\n"
                print "mmplot error: Bad usage in plotitems! Impossible to plot graph. Please, use help.\n"
                return 0
        # PNG file
        if filename:
            g.hardcopy(filename, terminal='png', color=1)
        fig = outfig
        return fig

[`mmbshow`] [Up] [`mmvdome`] |
Copyright (c) 2003, Roberto A. Lotufo, UNICAMP-University of Campinas; Rubens C. Machado, CenPRA-Renato Archer Research Center.