Reputation: 175
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!
Upvotes: 7
Views: 10995
Reputation: 113
A combination of
fig.patch.set_visible(False)
self.setStyleSheet("background-color:transparent;")
works for me (self is a subclass of Canvas). Any of these two alone do not work.
Upvotes: 0
Reputation: 175
I solved it this way. It's not ideal, but it works.
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
from matplotlib.colors import ColorConverter
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()
win = Gtk.Window()
style = win.get_style_context()
bg_colour = style.get_background_color(
Gtk.StateType.NORMAL).to_color().to_floats()
cc = ColorConverter()
cc.to_rgba(bg_colour)
fig.patch.set_facecolor(bg_colour)
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()
Upvotes: 2
Reputation: 5531
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)
Upvotes: 3