如何在PyQt中调整绘图的大小?

时间:2017-06-03 16:10:27

标签: python matplotlib plot label pyqt5

我找到了以下代码here。我减少了一些代码,使其更适合我的问题。

import sys
import matplotlib
matplotlib.use("Qt5Agg")
from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject
from PyQt5.QtWidgets import *
from numpy import arange, sin, pi
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

class MyMplCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""
    def __init__(self, parent=None, width = 5, height = 3, dpi=100):

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

        self.compute_initial_figure()
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)

        FigureCanvas.updateGeometry(self)

class MyStaticMplCanvas(MyMplCanvas):
    """Simple canvas with a sine plot."""
    def compute_initial_figure(self):
        t = arange(0.0, 3.0, 0.01)
        s = sin(2*pi*t)
        self.axes.plot(t, s)
        self.axes.set_ylabel('label2')
        self.axes.set_xlabel('label1')
        self.axes.grid(True)

class ApplicationWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setMinimumWidth(800)
        self.setMinimumHeight(300)
        self.setMaximumWidth(800)
        self.setMaximumHeight(300)

        self.main_widget = QWidget(self)

        self.sc = MyStaticMplCanvas(self.main_widget, width=5, height=4, dpi=100)

        l = QVBoxLayout(self.main_widget)
        l.addWidget(self.sc)
        self.setCentralWidget(self.main_widget)

if __name__ == '__main__':
    app = QApplication(sys.argv)

    aw = ApplicationWindow()
    aw.setWindowTitle("PyQt5 Matplotlib Example")
    aw.show()
    app.exec_()

问题在于原则上正确显示了图表,但缺少x标签(从显示的框架中掉出)。那么,如何调整axis对象的大小以使PyQt 也显示x-label

我知道数字大小可以通过' figsize'来调整。论点。但到目前为止,我无法在图中找到类似的图表命令。

另外,我听说matplotlib的gridspec软件包,但我认为它不适合这里,因为我只有一个图表要显示。

2 个答案:

答案 0 :(得分:1)

您可能需要阅读thight layout guide

所以一个选择是打电话

 <activity
            android:name=".CameraActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme_NoActionBar" />

您还可以adjust the subplot parameters

self.fig.tight_layout()

您还可以set the position

self.fig.subplots_adjust(0.2, 0.2, 0.8, 0.8) # left,bottom,right,top 

答案 1 :(得分:0)

我解决了问题,事实证明人们可以通过位置参数简单地调整轴。

self.ax = self.fig.add_subplot(111, position=[0.15, 0.15, 0.75, 0.75])