20
Июл
2021

как сделать чтобы график равномерно распределился по всей канве (matplotlib)

Сейчас у меня код, которую вы видите внизу (график в реальном времени). При добавлении данных мне нужно чтобы график не сжимался, а равномерно распределился и бы могла увидеть график в помощью скроллинга.введите сюда описание изображения <--такое нужно получить. И я попыталась сделать что-то, но у меня сам скроллинг работает но график все так же сжимается. Спасибо заранее за помощь и за любой совет!

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.animation import FuncAnimation
import numpy as np
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT
import mplcursors
from collections import deque

plt.style.use('seaborn-whitegrid')

def animation(i, axs):
    data = pd.read_csv('FlyData.txt', sep='\s+', encoding='latin-1', header=None)
    data = pd.DataFrame(data)
    colors = ['#FFD700', 'g', 'b', 'r', 'purple', 'c', 'm', 'y', 'k', 'c', '#FF4500', '#2F4F4F', '#FF69B4', '#556B2F', '#20B2AA', '#BDB76B', '#FFD700', '#DB7093', '#7FFF00', '#4B0082']
    labels = ['hr', 'Vпр, м\с', 'c', 'gh', 'h', 'j', 'h']
    x = data[0]
    m = 0
    for i in range(0, 7):
        y = data[i+1]
        ymax = max(y)
        ymin = min(y)
        stepx = max(x)/10
        axs[i].clear()
        axs[i].label_outer()
        axs[i].set_ylim([ymin*1.1, ymax*1.1])
        axs[i].set_xticks(np.arange(0, max(x)+1, stepx))
        axs[i].spines['right'].set_visible(False)
        axs[i].spines['top'].set_visible(False)
        axs[i].set_ylabel(labels[i])
        axs[i].plot(x, y, colors[i])

        if ymax > 1000 and ymax>2000:
            axs[i].set_yticks(np.arange(ymin, ymax, 400))
        elif ymax < 1000 and ymax>500:
            axs[i].set_yticks(np.arange(ymin, ymax, 200))
        elif ymax>100 and ymax<500:
            axs[i].set_yticks(np.arange(ymin, ymax, 50))
        elif ymax<100 and ymax>15:
            axs[i].set_yticks(np.arange(ymin, ymax, 20))
        elif ymax<15 and ymax>1:
            axs[i].set_yticks(np.arange(ymin, ymax, 2))
        else:
            axs[i].set_yticks(np.arange(ymin, ymax, 0.20))

        #DATA_POINTS_TO_DISPLAY = 200
        #data1 = deque(maxlen=DATA_POINTS_TO_DISPLAY)

    plt.xlabel('Время')
    mplcursors.cursor(hover=True)


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1119, 821)


        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")

        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setObjectName("pushButton")
        self.gridLayout.addWidget(self.pushButton, 0, 0, 1, 1)

        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setObjectName("pushButton_2")
        self.gridLayout.addWidget(self.pushButton_2, 0, 1, 1, 1)

        self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_3.setObjectName("pushButton_3")
        self.gridLayout.addWidget(self.pushButton_3, 0, 2, 1, 1)

        self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_4.setObjectName("pushButton_4")
        self.gridLayout.addWidget(self.pushButton_4, 0, 3, 1, 1)

        self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_5.setObjectName("pushButton_5")
        self.gridLayout.addWidget(self.pushButton_5, 0, 4, 1, 1)

        self.pushButton_6 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_6.setObjectName("pushButton_6")
        self.gridLayout.addWidget(self.pushButton_6, 0, 5, 1, 1)

        self.figure = plt.figure()
        self.gs = self.figure.add_gridspec(7, hspace=0)
        self.axs = self.gs.subplots(sharex=True, sharey=False)
        self.figure.tight_layout()

        #self.figure.canvas.mpl_connect('button_press_event', onClick)
        #anim_running = True
        self.ani = FuncAnimation(self.figure, animation, fargs=(self.axs,), interval=1000, blit = False)
        self.canvas = FigureCanvasQTAgg(self.figure)
        self.toolbar = NavigationToolbar2QT(self.canvas, self.canvas)
        self.gridLayout.addWidget(self.canvas, 1, 0, 1, 18)
        self.canvas.draw()


        #self.widget = QtWidgets.QWidget(self.centralwidget)
        #self.widget.setObjectName("widget")
        #self.gridLayout.addWidget(self.widget, 1, 0, 1, 6)
        step = 1
        self.step = step
        #self.scroll = QtWidgets.QScrollArea(self.centralwidget)
        #self.scroll.setWidget(self.canvas)
        #self.scroll.setWidgetResizable(True)
        #self.gridLayout.addWidget(self.scroll,  2, 0, 1, 18)
        self.scroll = QtWidgets.QScrollBar(self.centralwidget)
        self.scroll.setOrientation(QtCore.Qt.Horizontal)
        self.scroll.setPageStep(self.step * 100)
        self.scroll.setObjectName("scroll")
        self.gridLayout.addWidget(self.scroll,  2, 0, 1, 18)
        self.setupSlider()
        #self.scroll.sliderMoved.connect(self.canvas)

        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "PushButton"))
        self.pushButton_2.setText(_translate("MainWindow", "PushButton"))
        self.pushButton_3.setText(_translate("MainWindow", "PushButton"))
        self.pushButton_4.setText(_translate("MainWindow", "PushButton"))
        self.pushButton_5.setText(_translate("MainWindow", "PushButton"))
        self.pushButton_6.setText(_translate("MainWindow", "PushButton"))

    def setupSlider(self):

        self.lims = np.array(self.axs[0].get_xlim())
        self.scroll.setPageStep(self.step * 100)
        self.scroll.actionTriggered.connect(self.updatePage)
        self.updatePage()

    def updatePage(self, evt = None):
        r = self.scroll.value() / ((1 + self.step) * 100)
        l1 = self.lims[0] + r * np.diff(self.lims)
        l2 = l1 + np.diff(self.lims) * self.step
        self.axs[0].set_xlim(l1, l2)
        self.figure.canvas.draw_idle()

    #def stop_anim(self):
       #self.ani.event_source.stop()
       #self.ani.run ^= False

    #def onClick(event):
        #nonlocal anim_running
        #if anim_running:
            #ani.event_source.stop()
            #anim_running = False
        #else:
           # ani.event_source.start()
            #anim_running = True


if __name__ == '__main__':
    app = QtWidgets.QApplication.instance()
    if app is None:
        app = QtWidgets.QApplication(sys.argv)
        w1 = Ui_MainWindow()
        Form = QtWidgets.QMainWindow()
        w1.setupUi(Form)
        Form.show()
        app.exec_()

Источник: https://ru.stackoverflow.com/questions/1306901/%D0%BA%D0%B0%D0%BA-%D1%81%D0%B4%D0%B5%D0%BB%D0%B0%D1%82%D1%8C-%D1%87%D1%82%D0%BE%D0%B1%D1%8B-%D0%B3%D1%80%D0%B0%D1%84%D0%B8%D0%BA-%D1%80%D0%B0%D0%B2%D0%BD%D0%BE%D0%BC%D0%B5%D1%80%D0%BD%D0%BE-%D1%80%D0%B0%D1%81%D0%BF%D1%80%D0%B5%D0%B4%D0%B5%D0%BB%D0%B8%D0%BB%D1%81%D1%8F-%D0%BF%D0%BE-%D0%B2%D1%81%D0%B5%D0%B9-%D0%BA%D0%B0%D0%BD%D0%B2%D0%B5-matplotlib

Тебе может это понравится...

Добавить комментарий