Home > front end >  Why there are two duplicate axes labels when I embed Matplotlib figure inside a PyQt5 window?
Why there are two duplicate axes labels when I embed Matplotlib figure inside a PyQt5 window?

Time:09-23

I am trying to embed a Matplotlib Plot in a PyQt5 Window. I am using the following code:

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton
import sys
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

import numpy as np


class Window(QMainWindow):
    def __init__(self):

        super().__init__()
        title ='Matplotlib Embedding In PyQt5'
        top=  400
        left = top
        width = 900
        height = 500
        self.setWindowTitle(title)
        self.setGeometry(left, top, width, height)
        self.ui()

    def ui(self):
        canvas1 = Canvas(self, width=4, height=4)

        button = QPushButton('Click me', self)
        button.move(250, 450)
        self.plot(canvas1)

    def plot(self, canvas):
        x= np.linspace(0, 1, 200)
        y = np.sinc(x)
        ax = canvas.figure.add_subplot(111)
        ax.plot(x,y)

class Canvas(FigureCanvas):
    def __init__(self, parent=None, width=5, height=5, dpi = 100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        


app = QtWidgets.QApplication(sys.argv)

main_window = Window()
main_window.show()

sys.exit(app.exec())

However, when I run that (using Python 3.8.10), I get:

enter image description here

As you can see, there is something wrong with the axes labels.

How can I fix that?

CodePudding user response:

You are creating 2 axes:

self.axes = fig.add_subplot(111)
ax = canvas.figure.add_subplot(111)

The solution is to reuse the existing axes:

def plot(self, canvas):
    x = np.linspace(0, 1, 200)
    y = np.sinc(x)
    canvas.axes.plot(x, y)

Or clean the figure before:

def plot(self, canvas):
    x = np.linspace(0, 1, 200)
    y = np.sinc(x)
    canvas.figure.clear()
    ax = canvas.figure.add_subplot(111)
    ax.plot(x, y)
  • Related