我在组合wxPython和matplotlib的应用程序上苦苦挣扎。
我想在wxPanel中嵌入一个动画matplotlib对象。数据应该在运行时添加。
我的模块代码:
(我无法获得正确的格式,请参阅http://pastebin.com/PU5QFEzG)
'''
a panel to display a given set of data in a wxframe as a heatmap, using pcolor
from the matplotlib
@author: me
'''
import wx
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas #todo: OW 26.10.15 needed?
class plotPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.figure = plt.Figure()
self.subplot = self.figure.add_subplot(111)
plt.title('test')
self.canvas = FigureCanvas(self, -1, self.figure) #ToDo: OW 26.10.15 Verstehen
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
self.SetSizer(self.sizer)
self.Fit()
self.dataSet = []
self.animator = animation.FuncAnimation(self.figure,self.anim, interval=1000)
def anim(self, a):
if(len(self.dataSet) == 0):
return 0
i = a % len(self.dataSet)
obj = self.subplot.pcolor(self.dataSet[i], cmap='RdBu')
return obj
def add_data(self, data):
self.dataSet.append(data)
#
# Code for a standalone test run
#
class TestFrame(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self,parent,title=title,size=(1000,1000))
self.statusbar = self.CreateStatusBar()
self.statusbar.SetStatusText('Status Bar')
if __name__ == '__main__':
from numpy.random import rand #todo: OW 26.10.15 remove
app = wx.App(redirect=False)
frame = TestFrame(None, 'Debug Frame')
panel = plotPanel(frame)
frame.Show()
C = rand(10,10)
panel.add_data(C)
C = rand(10,10)
panel.add_data(C)
C = rand(10,10)
panel.add_data(C)
app.MainLoop()
我现在正在努力向图表添加更多细节,例如彩条或标题。
如果我在anim_Fkt中添加self.subplot.title = 'test'
,我会得到"' str'对象没有属性' get_animated'"。如果我尝试plt.title('test')
,则无效。
什么是添加标题或颜色栏或图例的正确方法?
答案 0 :(得分:0)
要将功能添加到嵌入式matplotlib图中,必须使用面向对象的matplotlib API。 matplotlib图由一个图(一个matplotlib.figure.Figure
实例)组成,其中包含一个或多个轴(matplotlib.axes.Axes
个实例)。它们中的每一个都包含Drawables
(线条,图像,散点图等)。
可以使用setter方法将标题添加(或修改)到Figure
或每个Axes
,例如Figure.suptitle
或Axes.set_title
(或者,在您的情况下) ,self.figure.suptitle()
或self.subplot.set_title
)。
colorbar有点棘手,因为它需要创建一个数据对象(可映射):我们只能在anim
函数中创建它。另外,我不想创建许多colorbar
个实例;一旦创建,我们只需要更新它。实现这一点很简单:在构造函数中使用self.colorbar
实例化None
,然后在动画函数中对None
进行检查:如果是None
,则创建颜色条,如果是不,然后更新它:
class plotPanel(wx.Panel):
def __init__(self, parent):
...
self.colorbar = None
def anim(self, a):
...
self.subplot.set_title("Frame %i" % a)
if self.colorbar is None:
self.colorbar = self.figure.colorbar(obj)
else:
self.colorbar.update_normal(obj)
self.colorbar.update_normal(obj)
return obj