matplotlib and transparency figure

前端 未结 1 899
难免孤独
难免孤独 2020-12-11 09:15

I am working with the matplotlib library and PyQt5 with Python 3.6. I add a figure in a window I create, and I wish to set transparent

1条回答
  •  时光说笑
    2020-12-11 09:53

    The problem occurs because the background image is set as a palette to the widget. This causes the canvas to inherit the palette and hence the canvas will also have the image as background, somehow overlaying the widget's background.

    A solution would be to set the background of the canvas transparent. An easy way to do so are style sheets.

    self.canvas.setStyleSheet("background-color:transparent;")
    

    Note that this is not the same as setting the patches' facecolor to none. The figure has a background, which is controlled inside matplotlib, but the canvas, being a PyQt object also has a background.

    Complete example:

    import sys, os
    from PyQt4.QtCore import Qt
    from PyQt4.QtGui import *
    
    import matplotlib
    matplotlib.use('Qt4Agg') 
    from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
    from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
    from matplotlib.figure import Figure
    import matplotlib.pyplot as plt
    plt.rcParams['xtick.color'] ="w"
    plt.rcParams['ytick.color'] ="w"
    plt.rcParams['font.size'] = 14
    
    
    class SecondWindow(QWidget):
        def __init__(self, parent=None):
            super(SecondWindow, self).__init__(parent)
    
            # CREATE FIGURE AND SETTINGS
            self.figure = plt.figure()
            self.figure.patch.set_facecolor("None")
            self.canvas = FigureCanvas(self.figure)
            self.axes = self.figure.add_subplot(111)
            self.axes.patch.set_alpha(0.5)
    
            ###### Make the background of the canvas transparent
            self.canvas.setStyleSheet("background-color:transparent;")
    
            self.p = QPalette()
            self.p.setBrush(QPalette.Background, QBrush(QPixmap("house.png")))
            self.setPalette(self.p)
    
            self.setLayout(QVBoxLayout())
            self.layout().addWidget(self.canvas,1)
            self.layout().setContentsMargins(50, 50, 50, 50)
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        form = SecondWindow()
        form.show()
        sys.exit(app.exec_())
    

    which might then look like

    0 讨论(0)
提交回复
热议问题