当我在 PyQt5 窗口中嵌入 Matplotlib 图形时,为啥有两个重复的轴标签?
Posted
技术标签:
【中文标题】当我在 PyQt5 窗口中嵌入 Matplotlib 图形时,为啥有两个重复的轴标签?【英文标题】:Why there are two duplicate axes labels when I embed Matplotlib figure inside a PyQt5 window?当我在 PyQt5 窗口中嵌入 Matplotlib 图形时,为什么有两个重复的轴标签? 【发布时间】:2021-09-22 19:12:19 【问题描述】:我正在尝试在 PyQt5 窗口中嵌入 Matplotlib 图。我正在使用以下代码:
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())
但是,当我运行它时(使用 Python 3.8.10),我得到:
如您所见,坐标轴标签有问题。
我该如何解决这个问题?
【问题讨论】:
【参考方案1】:您正在创建 2 个轴:
self.axes = fig.add_subplot(111)
ax = canvas.figure.add_subplot(111)
解决方案是重用现有的轴:
def plot(self, canvas):
x = np.linspace(0, 1, 200)
y = np.sinc(x)
canvas.axes.plot(x, y)
或者清理之前的图:
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)
【讨论】:
以上是关于当我在 PyQt5 窗口中嵌入 Matplotlib 图形时,为啥有两个重复的轴标签?的主要内容,如果未能解决你的问题,请参考以下文章