Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force background of matplotlib figure to be transparent

I'm trying to include a matplotlib figure in a Python Gtk3 application I'm writing. I'd like to set the background colour of the figure to be transparent, so that the figure just shows up against the natural grey background of the application, but nothing I've tried so far seems to be working.

Here's an MWE:

from gi.repository import Gtk
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import numpy as np
from matplotlib.backends.backend_gtk3agg import FigureCanvasGTK3Agg as FigureCanvas

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        fig, ax = plt.subplots()
        #fig.patch.set_alpha(0.0)
        x,y = np.array([[0, 1], [0, 0]])
        line = mlines.Line2D(x, y, c='#729fcf')
        ax.add_line(line)
        plt.axis('equal')
        plt.axis('off')

        fig.tight_layout()

        sw = Gtk.ScrolledWindow()
        sw.set_border_width(50)
        canvas = FigureCanvas(fig)
        sw.add_with_viewport(canvas)

        layout = Gtk.Grid()
        layout.add(sw)

        self.add(layout)

win = MyWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

If the fig.patch.set_alpha(0.0) line is uncommented, the colour of the background just changes to white, rather than grey. All suggestions greatly appreciated!

like image 734
Donagh Avatar asked Oct 08 '13 22:10

Donagh


1 Answers

It seems to me that it's the axes background that needs to be hidden. You might try using ax.patch.set_facecolor('None') or ax.patch.set_visible(False).

Alternatively, have you tried setting both the figure and axes patches off? This may be accomplished by:

for item in [fig, ax]:
    item.patch.set_visible(False) 
like image 170
spinup Avatar answered Oct 05 '22 02:10

spinup