0

"According to this SO note, one should not import pyplot when embedding. It does funky things like running its own GUI with its own main loop."

If so, how can one pass the matplotlib.axes._axes.Axes argument necessary for a Slider without invoking plt.axes()? In the GUI based on matplotlib documentation, we have [added the following to include a slider]:

 def compute_initial_figure(self):
        ymax = 300
        window_size=1
        res= 0.1
        ax= self.axes
        t = np.arange(0.0, 100.0, 0.1)
        s = np.sin(2*np.pi*t)
        ax.plot(t, s)
        ax.axis([0, window_size, -ymax, ymax])
        ax.get_xaxis().get_major_formatter().set_useOffset(False)
        axcolor = 'lightgoldenrodyellow'
        axpos = plt.axes([.1, .1, 0.75, 0.05], axisbg=axcolor) #MAKES OWN FIG!
        spos = Slider(axpos, 'Time', res, t[-1], valinit=0)
        spos.on_changed(update)

The axpos line uses plt and creates its own figure separate from the Qt window. Note plt.axes returns a a matplotlib.axes._axes.Axes object not a matplotlib.axes._subplots.AxesSubplot object.

Similar questions:
When matplotlib is embedded in PyQt4 how are axes/subplots labelled without using pyplot?
Combining PyQt and Matplotlib

Community
  • 1
  • 1
Rubenulis
  • 1,738
  • 1
  • 10
  • 10

1 Answers1

1

The plt.axes function adds an axes to the current figure by getting the current figure and then calling figure.add_axes. Instead of getting the current figure you must keep a reference to the figure when you create it. If you look at http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html, you can see how a figure should be created. I would take that example as a starting point.

So, to keep a reference to the figure change the relevant line into:

self.fig = Figure(figsize=(width, height), dpi=dpi)

Then call the add_axes method like this:

axpos = self.fig.add_axes([.1, .1, 0.75, 0.05], axisbg=axcolor)
titusjan
  • 5,376
  • 2
  • 24
  • 43
  • thanks for your reply. It seems fig.axes is TYPE: and not matplotlib.axes._axes.Axes so it produces a TypeError: 'list' object is not callable. Still working it out. – Rubenulis Jul 06 '16 at 16:32
  • Ah, I didn't look right. Looking again at the source of `pyplot.axes` I see that it calls `add_axes` on the current figure. I will update my post above. – titusjan Jul 06 '16 at 21:48
  • Perfect. Thank you. Also, for the purposes of the slider: 1) It wants canvas defined (self.canvas= FigureCanvas.__init__(self, fig)) before the compute_initial_figure(). 2) Similarly, in the example the figure is defined as fig but I changed it to sel.fig to facilitate using it later. – Rubenulis Jul 07 '16 at 00:42