【问题标题】:How can you change how a matplotlib figure/axes is stretched when resizing the parent window in PyQt5?在 PyQt5 中调整父窗口大小时,如何更改 matplotlib 图形/轴的拉伸方式?
【发布时间】:2020-05-28 00:47:14
【问题描述】:

我有一个带有嵌入式图形的程序,该程序还显示带有自定义刻度标签的颜色条。但是,图形的自动调整大小会切断部分刻度标签。如果我可以简单地手动调整窗口大小以便再次显示所有内容,这不会太糟糕。但是,当您调整窗口大小时,图形会以这样一种方式拉伸,即在左侧创建了一个大的空白区域,而右侧的刻度标签仍然无法完全看到,除非您将窗口拉伸得不必要的宽。我怎样才能改变这种行为? 下面是一个例子。如您所见,我已经尝试了一些方法,但都没有奏效。

import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import \
    FigureCanvasQTAgg as FigureCanvas
import matplotlib.ticker as mticker


from PyQt5.QtWidgets import QApplication, QDialog, QGridLayout
from PyQt5.QtCore import QSize


class MathTextSciFormatter(mticker.Formatter):
    def __init__(self, fmt="%1.1e"):
        self.fmt = fmt

    def __call__(self, x, pos=None):
        s = self.fmt % x
        decimal_point = '.'
        positive_sign = '+'
        tup = s.split('e')
        significand = tup[0].rstrip(decimal_point)
        sign = tup[1][0].replace(positive_sign, '')
        exponent = tup[1][1:].lstrip('0')
        if exponent:
            exponent = '10^{%s%s}' % (sign, exponent)
        if significand and exponent:
            s = r'%s{\times}%s' % (significand, exponent)
        else:
            s = r'%s%s' % (significand, exponent)
        return "${}$ W/m${{}}^2$".format(s)


class Test(QDialog):
    def __init__(self):
        super().__init__()
        self.lay = QGridLayout(self)
        self.fig, self.ax = plt.subplots()
        # self.ax.set_anchor('SW')
        # self.ax.set_position([0, 0, 0, 0])
        # self.fig.tight_layout()
        # self.ax.margins(0, 0)
        self.canvas = FigureCanvas(self.fig)
        self.lay.addWidget(self.canvas)
        self.resize(QSize(380, 290))
        self.setMaximumHeight(290)
        self.image = np.reshape(np.random.randint(0, 1000, 10000), (100, 100))
        self.image_artist = self.ax.imshow(self.image)
        self.colorbar = self.fig.colorbar(self.image_artist)
        self.colorbar.ax.yaxis.set_major_formatter(
            MathTextSciFormatter()
        )


if __name__ == '__main__':
    app = QApplication(sys.argv)
    test = Test()
    test.show()
    sys.exit(app.exec_())

【问题讨论】:

标签: python matplotlib pyqt pyqt5


【解决方案1】:

正如 ImportanceOfBeingErnest 在评论中指出的那样,使用 constrained_layout 就可以了。

import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import \
    FigureCanvasQTAgg as FigureCanvas
import matplotlib.ticker as mticker


from PyQt5.QtWidgets import QApplication, QDialog, QGridLayout
from PyQt5.QtCore import QSize


class MathTextSciFormatter(mticker.Formatter):
    def __init__(self, fmt="%1.1e"):
        self.fmt = fmt

    def __call__(self, x, pos=None):
        s = self.fmt % x
        decimal_point = '.'
        positive_sign = '+'
        tup = s.split('e')
        significand = tup[0].rstrip(decimal_point)
        sign = tup[1][0].replace(positive_sign, '')
        exponent = tup[1][1:].lstrip('0')
        if exponent:
            exponent = '10^{%s%s}' % (sign, exponent)
        if significand and exponent:
            s = r'%s{\times}%s' % (significand, exponent)
        else:
            s = r'%s%s' % (significand, exponent)
        return "${}$ W/m${{}}^2$".format(s)


class Test(QDialog):
    def __init__(self):
        super().__init__()
        self.lay = QGridLayout(self)
        self.fig, self.ax = plt.subplots(constrained_layout=True)
        # self.ax.set_anchor('SW')
        # self.ax.set_position([0, 0, 0, 0])
        # self.fig.tight_layout()
        # self.ax.margins(0, 0)
        self.canvas = FigureCanvas(self.fig)
        self.lay.addWidget(self.canvas)
        self.resize(QSize(380, 290))
        self.setMaximumHeight(290)
        self.image = np.reshape(np.random.randint(0, 1000, 10000), (100, 100))
        self.image_artist = self.ax.imshow(self.image)
        self.colorbar = self.fig.colorbar(self.image_artist)
        self.colorbar.ax.yaxis.set_major_formatter(
            MathTextSciFormatter()
        )


if __name__ == '__main__':
    app = QApplication(sys.argv)
    test = Test()
    test.show()
    sys.exit(app.exec_())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    • 2011-10-01
    • 2023-03-24
    相关资源
    最近更新 更多