首页 > 解决方案 > 如何使用 Canvas/Matplotlib 绘制一条线?

问题描述

我正在尝试使用画布和 matplotlib 绘制一条线。

我已经有了这个数字,还有其他一切。但是当我尝试使用命令 plot(self.axes.plot()) 它不起作用。

有谁知道发生了什么??可能有一些我遗漏的细节,但我找不到它!

import sys
from PyQt5.QtWidgets import *
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib import pyplot as plt

class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Plotting")
        self.setGeometry(50, 50, 700, 700)
        self.UI()
        self.show()

    def UI(self):
        # Cria o canvas para exibição dos entes da estrutura ------------------
        self.dpi = 70
        self.fig = Figure((5.0, 5.0), dpi=self.dpi, frameon=False, tight_layout=True)
        self.canvas = FigureCanvas(self.fig)
        self.axes = self.fig.add_subplot(111)

        # Cria grid de plotagem (axes) ----------------------------------------
        self.load_axes()

        layout = QGridLayout()

        layout.addWidget(self.canvas, 0, 0)

        self.setLayout(layout)

        self.plotar()

    def plotar(self):
        self.axes.clear()
        self.load_axes()
        self.axes.plot([0, 0], [1, 1], linestyle = '-', color = 'black', linewidth=5.5, zorder = 0)

        # Define a área de plotagem -------------------------------------------
        self.axes.relim()
        # Plota todas as linhas no canvas -------------------------------------
        self.fig.canvas.draw()

    def load_axes(self):
        self.axes.axis('equal')
        self.axes.set_xmargin(.4)
        self.axes.set_ymargin(.4)
        self.axes.autoscale_view(tight=True)
        self.axes.xaxis.set_major_locator(plt.MultipleLocator(5.0))
        self.axes.xaxis.set_minor_locator(plt.MultipleLocator(1.0))
        self.axes.yaxis.set_major_locator(plt.MultipleLocator(5.0))
        self.axes.yaxis.set_minor_locator(plt.MultipleLocator(1.0))
        self.axes.grid(which='major', axis='x', linewidth=0.75, linestyle='-', color='gainsboro')
        self.axes.grid(which='minor', axis='x', linewidth=0.50, linestyle='-', color='gainsboro')
        self.axes.grid(which='major', axis='y', linewidth=0.75, linestyle='-', color='gainsboro')
        self.axes.grid(which='minor', axis='y', linewidth=0.50, linestyle='-', color='gainsboro')


def main():
    App = QApplication(sys.argv)
    window = Window()
    sys.exit(App.exec_())

if __name__=='__main__':
    main()


标签: pythonmatplotlibcanvasplot

解决方案


看起来它实际上画得很好,没问题,但是您为轴指定的范围存在问题。

您已指定: self.axes.plot([0, 0], [1, 1], linestyle = '-', color = 'black', linewidth=5.5, zorder = 0)

这意味着您要求 x 轴显示 0 到 0 的范围,y 轴显示 1 到 1。尝试将其更改为:

self.axes.plot([0, 1], [0, 1], linestyle = '-', color = 'black', linewidth=5.5, zorder = 0)

那应该显示你的行!:-D


推荐阅读