How to plot several graphs and make use of the navigation button in [matplotlib]

Question:

The latest version of matplotlib automatically creates navigation buttons under the graph. However, the examples I see in the Internet all just show how to create one graph, thus making the button [Next] and [Previous] useless. How do I plot several graphs and make use of those buttons?

For example I want to make graph for sin() and cos() from 0 degree to 360 degree.

Right now I do it like this:

import scipy
from matplotlib import pyplot

DataRange = range(0, 360)
DataRange = map(scipy.deg2rad, DataRange)
Data1 = map(scipy.sin, DataRange)
Data2 = map(scipy.cos, DataRange)
pyplot.plot(Data1)
pyplot.show()   # <--- if I exclude this
pyplot.plot(Data2)
pyplot.show()

The sin() graph will be shown. It is when I close the window that the cos graph will be shown. If I exclude the first pyplot.show(), both will be shown in the same figure.

How to make it so that the second graph is shown when I press the Next button?

Asked By: 絢瀬絵里

||

Answers:

According to the documentation, the Forward and Back buttons are used to allow you to go back to a previous view of a single figure. So for example if you used the Zoom-to-rectangle feature, the Back button would return you to the previous display. Depending on your backend, it is possible hook when these buttons are pressed.

You can obviously plot several graphs at the same time using subplot as follows:

import scipy
from matplotlib import pyplot

DataRange = range(0, 360)
DataRange = map(scipy.deg2rad, DataRange)
Data1 = map(scipy.sin, DataRange)
Data2 = map(scipy.cos, DataRange)

pyplot.subplot(211)
pyplot.plot(Data1)
pyplot.subplot(212)
pyplot.plot(Data2)
pyplot.show()

Giving you:

enter image description here

Alternatively, you could alternate between your two figures when they are clicked on using the following:

import scipy
from matplotlib import pyplot

DataRange = range(0, 360)
DataRange = map(scipy.deg2rad, DataRange)
Data1 = map(scipy.sin, DataRange)
Data2 = map(scipy.cos, DataRange)

toggle = True

def onclick(event):
    global toggle

    toggle = not toggle
    event.canvas.figure.clear()

    if toggle:
        event.canvas.figure.gca().plot(Data1)
    else:
        event.canvas.figure.gca().plot(Data2)

    event.canvas.draw()

fig = pyplot.figure()
fig.canvas.mpl_connect('button_press_event', onclick)

pyplot.plot(Data1)
pyplot.show()
Answered By: Martin Evans

Those prev/next buttons are not for navigating through different plots; they allow the viewer to navigate through the ‘views’ he has chosen with pan/zoom and zoom-rectangle. In that sense, ‘home’ is just a shortcut for pressing ‘previous’ a bunch of times.

Answered By: RubeRad
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.