gpt4 book ai didi

python-3.x - 为什么 Matplotlib.rcParams.update 样式不更新 facecolor PyQt5?

转载 作者:行者123 更新时间:2023-12-05 01:18:34 25 4
gpt4 key购买 nike

我正在使用 matplotlib 样式,当在组合框中选择样式时,我尝试动态更改样式。我使用的是 Matplotlib 2.2.3、Python 3.6.6、PyQt5、Windows 10。但是当我选择 dark_background 样式时,图形 facecolor 和轴 facecolor 不会改变。这里有一个动画: dark_bakground error这是代码:

使用 pyuic5 生成的文件 IHMDrawDates.py:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MplMainWindow(object):
def setupUi(self, MplMainWindow):
MplMainWindow.setObjectName("MplMainWindow")
MplMainWindow.resize(628, 416)
self.centralwidget = QtWidgets.QWidget(MplMainWindow)
self.centralwidget.setObjectName("centralwidget")
self.gridLayout_2 = QtWidgets.QGridLayout(self.centralwidget)
self.gridLayout_2.setObjectName("gridLayout_2")
self.mpl = MplWidgetTest(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.mpl.sizePolicy().hasHeightForWidth())
self.mpl.setSizePolicy(sizePolicy)
self.mpl.setObjectName("mpl")
self.gridLayout_2.addWidget(self.mpl, 0, 0, 1, 1)
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setMaximumSize(QtCore.QSize(95, 16777215))
self.groupBox.setObjectName("groupBox")
self.gridLayout = QtWidgets.QGridLayout(self.groupBox)
self.gridLayout.setObjectName("gridLayout")
self.buttonDrawDate = QtWidgets.QPushButton(self.groupBox)
self.buttonDrawDate.setMaximumSize(QtCore.QSize(75, 16777215))
self.buttonDrawDate.setObjectName("buttonDrawDate")
self.gridLayout.addWidget(self.buttonDrawDate, 1, 0, 1, 1)
self.buttonErase = QtWidgets.QPushButton(self.groupBox)
self.buttonErase.setMaximumSize(QtCore.QSize(75, 16777215))
self.buttonErase.setObjectName("buttonErase")
self.gridLayout.addWidget(self.buttonErase, 2, 0, 1, 1)
spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.gridLayout.addItem(spacerItem, 3, 0, 1, 1)
self.comboTema = QtWidgets.QComboBox(self.groupBox)
self.comboTema.setObjectName("comboTema")
self.gridLayout.addWidget(self.comboTema, 0, 0, 1, 1)
self.gridLayout_2.addWidget(self.groupBox, 0, 1, 1, 1)
MplMainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MplMainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 628, 21))
self.menubar.setObjectName("menubar")
MplMainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MplMainWindow)
self.statusbar.setObjectName("statusbar")
MplMainWindow.setStatusBar(self.statusbar)

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

def retranslateUi(self, MplMainWindow):
_translate = QtCore.QCoreApplication.translate
MplMainWindow.setWindowTitle(_translate("MplMainWindow", "MainWindow"))
self.groupBox.setTitle(_translate("MplMainWindow", "GroupBox"))
self.buttonDrawDate.setText(_translate("MplMainWindow", "Draw"))
self.buttonErase.setText(_translate("MplMainWindow", "Erase"))

from mplwidgettest import MplWidgetTest

mplwidgettest.py 文件,其中包含用于更新 matplotlib 样式的“setTema”方法。当我打印变量 rcParams 时,它包含 axes.facecolor: black 但它不适用

from PyQt5.QtWidgets import QSizePolicy, QWidget, QVBoxLayout
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar)
import matplotlib as mplib


class MplCanvas(FigureCanvas):
"""Class to represent the FigureCanvas widget"""
def __init__(self):
# setup Matplotlib Figure and Axis
mplib.rcParams.update(mplib.rcParamsDefault)
mplib.style.use('bmh')
self.fig = Figure()
self.ax = self.fig.add_subplot(111)
# initialization of the canvas
FigureCanvas.__init__(self, self.fig)
# we define the widget as expandable
FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
# notify the system of updated policy
FigureCanvas.updateGeometry(self)

def setTema(self, tema='classic'):
print(tema)
mplib.style.use(tema)
print(mplib.rcParams)
mplib.rcParams.update(mplib.rcParams)


class MplWidgetTest(QWidget):
"""Widget defined in Qt Designer"""
def __init__(self, parent=None):
# initialization of Qt MainWindow widget
QWidget.__init__(self, parent)
# set the canvas to the Matplotlib widget
self.canvas = MplCanvas()
# create a NavigatioToolbar
self.ntb = NavigationToolbar(self.canvas, self)
# create a vertical box layout
self.vbl = QVBoxLayout()
# add mpl widget to vertical box
self.vbl.addWidget(self.canvas)
# add NavigationToolBar to vertical box
self.vbl.addWidget(self.ntb)
# set the layout to th vertical box
self.setLayout(self.vbl)

调用前两个文件的 mainMplWidget.py 文件,包含改变 matplotlib 样式的方法 'cambiarTema'

import sys
from IHMDrawDates import Ui_MplMainWindow
from PyQt5.QtWidgets import QMainWindow, QApplication
from PyQt5.QtGui import QCursor
import numpy as np


class DesignerMainWindow(QMainWindow, Ui_MplMainWindow):

def __init__(self, parent=None):
super(DesignerMainWindow, self).__init__(parent)
self.setupUi(self)
self.posX = []
self.posY = []
temas = ['bmh', 'classic', 'grayscale', 'seaborn-bright',
'ggplot', 'dark_background']
self.comboTema.addItems(temas)
# connect the signals with the slots
self.buttonDrawDate.clicked.connect(self.drawDate)
self.buttonErase.clicked.connect(self.eraseDate)
self.comboTema.currentIndexChanged.connect(self.cambiarTema)

def cambiarTema(self):
tema = self.comboTema.currentText()
self.mpl.canvas.setTema(str(tema))
self.mpl.canvas.ax.clear()
self.mpl.canvas.draw()
self.mpl.canvas.flush_events()

def drawDate(self):
x = np.arange(0, 100, 0.1)
y = np.sin(x)
self.mpl.canvas.ax.plot(x, y)
self.mpl.canvas.ax.relim()
self.mpl.canvas.ax.autoscale(True)
self.mpl.ntb.update()
self.mpl.ntb.push_current()
self.mpl.canvas.draw()

def eraseDate(self):
self.mpl.canvas.ax.clear()
self.mpl.ntb.update()
self.mpl.ntb.push_current()
self.mpl.canvas.draw()

if __name__ == '__main__':
app = 0
app = QApplication(sys.argv)
dmw = DesignerMainWindow()
# show it
dmw.show()
sys.exit(app.exec_())

最佳答案

下面解释为什么设置新的样式不会更新已有的图形。

matplotlib.rcParams本质上是一个字典,它存储了在 matplotlib 中创建对象时要使用的某些默认参数。rcParams.update 会更新这个字典; update是 python dict 对象的一个​​方法。 matplotlib.style.use是更新 rcParams 的快捷方式,它将从文件或字典中加载相应的参数。

然后在创建新对象时使用这些参数。以简化的方式,这看起来像

def create_object(arg1, parameter1=None):
if not parameter1:
# use the default from the rcParams
parameter1 = rcParams["parameter1"]
obj = MatplotlibObject(arg1, parameter1=parameter1)
return obj

创建对象时会用到这个函数。但是,一旦创建了这样的对象,当 rcParams 中的某些内容发生更改时,它不会再次运行。

obj = create_object(1)
rcParams.update({"parameter1" : "New Value"})
# at this point, obj would not know about the new parameter1 value

如前所述,有两种选择。

  • 手动更改参数。您可以在创建对象后手动更改参数。

    obj = create_object(1)
    obj.set_parameter1("New Value")
  • 重新创建对象。您可以删除现有对象,更新 rcParams 并重新创建对象,以便它使用新值。

    obj = create_object(1)
    del obj
    rcParams.update({"parameter1" : "New Value"})
    obj = create_object(1)

关于python-3.x - 为什么 Matplotlib.rcParams.update 样式不更新 facecolor PyQt5?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52007029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com