Dems314
Dems314

Reputation: 347

Matplotlib why does the plot function draw inside the button after i click?

hi i am trying to draw a graph in my plot after a button click event, problem is the graph is drawn inside the button instead of a normal plot.

heres the code :

import matplotlib.pyplot as plt
from matplotlib.widgets import Slider,Button

class Details:
    def drawPlot(self,event):
        plt.plot([1,3,4])
    def addTitle(self,title):
        plt.title(title)
    def plot(self):
        x = 1
        plt.show()
    def addButton(self):
        self.axnext = plt.axes([0.71, 0.1, 0.1, 0.075])
        self.bnext = Button(self.axnext, 'Next')
        self.bnext.on_clicked(self.drawPlot)


d = Details()
d.addTitle("cas dakar 1")
d.addButton()
d.plot()

thanks in advance !

Upvotes: 0

Views: 220

Answers (1)

tmdavison
tmdavison

Reputation: 69228

plt.plot draws on the current axes. So, when you create the axes for the button, that becomes the current axes, then you try to plot, and it plots there instead of your main axes.

If you switch to the object-oriented interface, this problem goes away:

import matplotlib.pyplot as plt
from matplotlib.widgets import Slider,Button

class Details:

    def __init__(self):
        fig, ax = plt.subplots()
        self.fig = fig
        self.ax = ax

    def drawPlot(self,event):
        self.ax.plot([1,3,4])

    def addTitle(self,title):
        self.ax.set_title(title)

    def plot(self):
        x = 1
        plt.show()

    def addButton(self):
        self.axnext = plt.axes([0.71, 0.1, 0.1, 0.075])
        self.bnext = Button(self.axnext, 'Next')
        self.bnext.on_clicked(self.drawPlot)


d = Details()
d.addTitle("cas dakar 1")
d.addButton()
d.plot()

Upvotes: 2

Related Questions