我正在编写一个使用 Matplotlib 进行绘图的 PyGTK/Twisted 应用程序。使用 FigureCanvasGtkAgg 将绘图嵌入到我的小部件中很容易,但我注意到 Canvas 的背景颜色(在绘图区域本身之外)与我的应用程序的其余部分不匹配,字体(对于标签)也不匹配、传说等)。
有没有一种简单的方法可以让我的图表尊重用户选择的 GTK 主题?
最佳答案
您可以通过例如 pylab.figure(facecolor=SOME_COLOR, ...)
设置它或 matplotlib.rcParams['figure.facecolor'] = SOME_COLOR
.看起来它的默认值是 hard-coded ,所以没有办法告诉 MPL 尊重 GTK 主题。
这是如何在 PyGTK 中执行此操作的具体示例。这里的一些信息来自 "Get colors of current gtk style"来自 gdk.Color文档。我还没有设置字体等,但这显示了您需要的基本框架。
首先,定义以下函数:
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)
然后您可以连接到
realize
信号(也可能是 map-event
信号,我没有尝试过)并在创建包含小部件时为图形重新着色:graph_panel.connect('realize', set_graph_appearance, graph.figure)
(这里,
graph_panel
是 gtk.Alignment
,graph
是 FigureCanvasGTKAgg
的子类,根据需要具有 figure
成员。)
关于matplotlib - 让 Matplotlib 的 GTK Agg 后端尊重用户主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5826760/