【问题标题】:PyQt5 with NavigationToolbar2QT missing change of color option for plt.fill_between()带有 NavigationToolbar2QT 的 PyQt5 缺少 plt.fill_between() 的颜色更改选项
【发布时间】:2019-12-21 23:36:45
【问题描述】:

如何在相应的导航工具栏中更改 plt.fill_between() 的颜色?所以基本上在 _line0 之外的曲线之间添加一个填充选项(见图)。或者,也可以根据线条的颜色来改变fill_between的误差。

我用facecolor=pl[0].get_color() 尝试了fill_between,但它并没有随着工具栏中的不同颜色选择而动态变化。

from PyQt5 import QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import sys

import pandas as pd
import numpy as np
from scipy import stats

class Example(QtWidgets.QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()
        self.draw()


    def initUI(self):
        self.canvasFigure = plt.figure(1)
        self.canvasWidget = FigureCanvas(self.canvasFigure)
        self.toolbar = NavigationToolbar(self.canvasWidget, self)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.canvasWidget)
        lay.addWidget(self.toolbar)

        self.resize(500, 400)


    def draw(self):
        ### generate random data
        df = pd.DataFrame(np.random.randint(0, 100, size=(100, 4)), columns=list('ABCD'))
        df_group_error = stats.sem(df, axis=1, nan_policy='omit')
        df_group = df.mean(axis=1)


        ### show in canvas
        self.canvasFigure.clear()

        fig = plt.figure(1)
        pl = plt.plot(df_group)
        plt.fill_between(df_group.index.tolist(), df_group - df_group_error, df_group + df_group_error, facecolor='red', alpha=0.2)

        self.canvasWidget.draw()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())

哪里应该可以改变fill_between颜色

【问题讨论】:

    标签: python matplotlib pyqt pyqt5


    【解决方案1】:

    您可以编写一个回调,在绘制图形时,将填充的颜色与线条的颜色相匹配。

    import matplotlib
    matplotlib.use("Qt5Agg")
    import numpy as np; np.random.seed(42)
    from matplotlib.colors import to_hex
    import matplotlib.pyplot as plt
    
    x = np.linspace(0,100)
    y = np.cumsum(np.random.randn(len(x)))+4
    err = np.random.rand(len(x))*0.5 + 1
    
    fig, ax = plt.subplots()
    fillb = ax.fill_between(x, y+err, y-err, alpha=0.4, facecolor="red", edgecolor="none")
    line, = ax.plot(x,y, color="blue")
    
    def update(evnt=None):
        c1 = line.get_color()
        c2 = fillb.get_facecolor().ravel()
        if to_hex(c1) != to_hex(c2):
            fillb.set_facecolor(line.get_color())
            fig.canvas.draw_idle()
    
    
    cid = fig.canvas.mpl_connect("draw_event", update)
    update()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-06
      • 2014-02-05
      • 1970-01-01
      • 2011-01-08
      • 2014-04-30
      • 2014-03-07
      相关资源
      最近更新 更多