7

I'm writing a PyGTK/Twisted app that uses Matplotlib for graphing. It's easy enough to embed the plots in my widgets using the FigureCanvasGtkAgg, but I notice that the background colour of the canvas (outside the plot area itself) does not match that for the rest of my application, and neither does the font (for labels, legends, etc).

Is there a simple way to get my graphs to respect the user selected GTK theme?

detly
  • 29,332
  • 18
  • 93
  • 152
  • I would like very much to take a look at your code, since I am trying to put pyplots in my widgets, too, or more precisely, to have just the figure to use inside the GUI – heltonbiker Jul 12 '11 at 21:16
  • @heltonbiker - you'll have to wait a few days, but I'll post a sample up when I have access to the code again. – detly Jul 12 '11 at 21:55

1 Answers1

3

You can set it by, for example pylab.figure(facecolor=SOME_COLOR, ...) or matplotlib.rcParams['figure.facecolor'] = SOME_COLOR. It looks like that its default value is hard-coded, so there is no way to tell MPL to respect GTK theme.


Here's a concrete example of how to do this in PyGTK. Some of this information here was gleaned from "Get colors of current gtk style" and from the gdk.Color docs. I haven't gotten as far as setting the font, etc, but this shows the basic framework you need.

First, define the following function:

def set_graph_appearance(container, figure):
    """
    Given a GTK container and a Matplotlib "figure" object, this will set the
    figure background colour to be the same as the normal colour of the
    container.
    """
    # "bg" is the background "style helper" object. It contains five different
    # colours, for the five different widget states.
    bg_style = container.get_style().bg[gtk.STATE_NORMAL]
    gtk_color = (bg_style.red_float, bg_style.green_float, bg_style.blue_float)
    figure.set_facecolor(gtk_color)

You can then connect to the realize signal (maybe also the map-event signal, I didn't try) and re-colour the graph when the containing widget is created:

graph_panel.connect('realize', set_graph_appearance, graph.figure)

(Here, graph_panel is a gtk.Alignment and graph is a subclass of FigureCanvasGTKAgg that has a figure member as needed.)

Community
  • 1
  • 1
tkf
  • 2,990
  • 18
  • 32
  • 3
    Great! This got me started, so I added some code illustrating how I've implemented changing the background to the GTK theme of the containing widget at the time of drawing. The only problem is that if a user changes theme after the graph is drawn, the graph will not change color. I think that's a sufficiently small edge-case to ignore. – detly Feb 09 '12 at 01:39
  • Great! Thnaks for the follow up. – tkf Feb 09 '12 at 11:18