Search code examples
matplotlibplotaxes

Matplotlib: why are plots always closed shapes?


Using 1.5.1 in Python 2.7.

I'm creating a figure, adding an axes object to it, creating a canvas, and putting it into a window. To draw a simple graph, I set the X and Y limits in the axes object, and then call the plot member function with a numpy arange of values and an array of y values of the same length, along with a few formatting options.

What I get is a nice graph of my data, but it is drawn as a closed curve, meaning that there is a diagonal line leading from the end of my graph back to the beginning.

Why would it do this? I can see the occasional utility of an option that does this, when the X values aren't monotonically increasing (say, to draw a polygon), but it hardly seems like a reasonable default. I don't see any axes attribute that would affect this, or any plot parameter. Does anyone know how to make it not wrap around like this?

EDIT: here is some sample code. It assumes PyGTK as the GUI environment:

import numpy
import gtk
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas

class junk:

    def __init__(self):

        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.connect('destroy', self.destroy)
        self.window.set_title('junk')
        self.window.resize(400, 400)

        self.figure = Figure()
        self.axes = self.figure.add_axes((0, 0, 1, 1))
        self.canvas = FigureCanvas(self.figure)
        self.canvas.show()

        self.window.add(self.canvas)

        self.axes.set_xlim(-10, 12)
        self.axes.set_ylim(-1, 122)
        x = numpy.arange(-9, 12)
        self.axes.plot(x, x * x, linestyle = 'solid')

        self.canvas.draw()

        self.window.show_all()

    def destroy(self, widget, data = None):

        gtk.main_quit()

    def main(self):

        gtk.main()

if __name__ == '__main__':

    app = junk()
    app.main()

This displays an off-center parabola, and the result looks like this:

enter image description here

Now change the lower Y limit from -1 to 1, so that it clips the bottom a little, and the result looks like this:

enter image description here

This shows that if more than one path is needed to draw the graph, each one has the spurious wraparound.

I'm doing this on Windows, but I had this same problem a couple years ago running on a Gumstix SOM running Linux.


Solution

  • BrenBarn identified the solution in the comment to the original post: use the GTKAgg backend instead of the GTK backend. Thanks.