0

How can I set the background color of my figures? I would like to use FigureCanvasQTAgg.

from PyQt5 import QtCore, QtWidgets, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.backends.backend_qt5 import NavigationToolbar2QT
from matplotlib.figure import Figure


class FigureCanvas(FigureCanvasQTAgg):
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvasQTAgg.__init__(self, self.fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(
            self,
            QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding,
        )
        FigureCanvas.updateGeometry(self)   
hko
  • 139
  • 3
  • 10

2 Answers2

3

Under usual circumstances there is no difference between the figure background and the canvas background. So you may set the figure background to some color

self.fig.set_facecolor("blue")

In case you do not want to change the figure's background color (I can't think of any reason right now, but maybe there is one use case), you would need to make the figure background transparent, such that the canvas background color can shine through,

self.fig.set_facecolor("none")
self.setStyleSheet("background-color:blue;")

This answer of mine gives some insight and also a test code to play with.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
1

I have never used matplotlib, nor tested this answer, but guessing here...

self.setStyleSheet("background-color:red;")

?

(based on some other answer)

Grzegorz Oledzki
  • 23,614
  • 16
  • 68
  • 106
  • 1
    The author of "some other answer" says: Yes, but.... you also need to make the figure transparent, such that the red color of the canvas background would be seen. See my answer. Btw. if you use the content of some other answer, wouldn't it be nice to upvote it - as using it somehow makes it useful, right? – ImportanceOfBeingErnest Nov 14 '17 at 20:10