本文整理汇总了Python中matplotlib.backends.backend_wxagg.FigureCanvasWxAgg.blit方法的典型用法代码示例。如果您正苦于以下问题:Python FigureCanvasWxAgg.blit方法的具体用法?Python FigureCanvasWxAgg.blit怎么用?Python FigureCanvasWxAgg.blit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.backends.backend_wxagg.FigureCanvasWxAgg
的用法示例。
在下文中一共展示了FigureCanvasWxAgg.blit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: PlotFigure
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
class PlotFigure(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, title="Sensor Monitor", size=(800, 600))
#set window size
self.fig = Figure((8, 6), 100)
self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig)
self.ax = self.fig.add_subplot(111)
self.ax.set_ylim([0, 100])
self.ax.set_xlim([0, POINTS])
self.ax.set_autoscale_on(False)
self.ax.set_xticks([])
self.ax.set_yticks(range(0, 101, 10))
self.ax.grid(True)
self.user = [None] * POINTS
self.l_user,=self.ax.plot(range(POINTS),self.user,label='Light Sensors')
self.ax.legend(loc='upper center',
ncol=4,
prop=font_manager.FontProperties(size=10))
self.canvas.draw()
self.bg = self.canvas.copy_from_bbox(self.ax.bbox)
wx.EVT_TIMER(self, TIMER_ID, self.onTimer)
def onTimer(self, evt):
self.canvas.restore_region(self.bg)
for i in range(0,240):
index = int(i/40)*40
per = (index-i)+20.0
per =((math.sin((per/20.0)*math.pi/2))+1.0)/2.0
self.user[i+30] = 100-(float(arr[i/40])*per+float(arr[(i+40)/40])*(1-per))*1
self.l_user.set_ydata(self.user)
self.ax.draw_artist(self.l_user)
self.canvas.blit(self.ax.bbox)
示例2: PlotFigure
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
class PlotFigure(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, title="CPU Usage Monitor", size=(600, 400))
# Matplotlib Figur
self.fig = Figure((6, 4), 100)
# bind the Figure to the backend specific canvas
self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig)
# add a subplot
self.ax = self.fig.add_subplot(111)
# limit the X and Y axes dimensions
self.ax.set_ylim([0, 100])
self.ax.set_xlim([0, POINTS])
self.ax.set_autoscale_on(False)
self.ax.set_xticks([])
# we want a tick every 10 point on Y (101 is to have 10
self.ax.set_yticks(range(0, 101, 10))
# disable autoscale, since we don't want the Axes to ad
# draw a grid (it will be only for Y)
self.ax.grid(True)
# generates first "empty" plots
self.user = [None] * POINTS
self.l_user,=self.ax.plot(range(POINTS),self.user,label='User %')
# add the legend
self.ax.legend(loc='upper center',
ncol=4,
prop=font_manager.FontProperties(size=10))
# force a draw on the canvas()
# trick to show the grid and the legend
self.canvas.draw()
# save the clean background - everything but the line
# is drawn and saved in the pixel buffer background
self.bg = self.canvas.copy_from_bbox(self.ax.bbox)
# bind events coming from timer with id = TIMER_ID
# to the onTimer callback function
wx.EVT_TIMER(self, TIMER_ID, self.onTimer)
self.Bind(wx.EVT_CLOSE,self.frame_close,self)
def onTimer(self, evt):
self.canvas.restore_region(self.bg)
# update the data
temp =np.random.randint(60,80)
self.user = self.user[1:] + [temp]
# update the plot
self.l_user.set_ydata(self.user)
# just draw the "animated" objects
self.ax.draw_artist(self.l_user)# It is used to efficiently update Axes data (axis ticks, labels, etc are not updated)
self.canvas.blit(self.ax.bbox)
print num
def frame_close(self,event):
self.Show(False)
def __del__(self):
exit()
示例3: PlotFigure
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
class PlotFigure(wx.Frame):
def __init__(self,data):
wx.Frame.__init__(self, None, wx.ID_ANY, title="CPU Usage Monitor", size=(600, 400))
# Matplotlib Figur
self.fig = Figure((6, 4), 100)
self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig)
# add a subplot
self.ax = self.fig.add_subplot(111)
self.data=data;
self.ax.set_ylim([0,100])
self.ax.set_xlim([0, POINTS])
self.ax.set_autoscale_on(False)
self.ax.set_xticks([])
self.ax.set_yticks(range(0,100, 5))
# disable autoscale, since we don't want the Axes to ad
# draw a grid (it will be only for Y)
self.ax.grid(True)
# generates first "empty" plots
self.user = [None] * POINTS
self.l_user,=self.ax.plot(range(POINTS),self.user,label=u'CPU percentage')
# add the legend
self.ax.legend(loc='upper center',
ncol=4,
prop=font_manager.FontProperties(size=10))
self.canvas.draw()
self.bg = self.canvas.copy_from_bbox(self.ax.bbox)
wx.EVT_TIMER(self, TIMER_ID, self.onTimer)
self.Bind(wx.EVT_CLOSE,self.frame_close,self)
def onTimer(self, evt):
self.canvas.restore_region(self.bg)
temp = (math.log(self.data.recvive())/LOG_FREQUENCE)*100
#temp =np.random.randint(60,80)
self.user = self.user[1:] + [temp]
# update the plot
self.l_user.set_ydata(self.user)
# just draw the "animated" objects
self.ax.draw_artist(self.l_user)# It is used to efficiently update Axes data (axis ticks, labels, etc are not updated)
self.canvas.blit(self.ax.bbox)
#print self.data.recvive()
def frame_close(self,event):
self.Show(False)
def __del__(self):
exit()
示例4: PlotFigure
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
class PlotFigure (wx.Frame):
def __init__ (self, groundTruth=None):
wx.Frame.__init__ (self, None, wx.ID_ANY, title="Trajectory")
self.fig = Figure ()
self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig)
self.ax = self.fig.add_subplot (111)
self.ax.set_xlim ([-600, 1000])
self.ax.set_ylim ([-1500, 1500])
self.ax.set_autoscale_on (False)
self.orbPos1 = None
self.orbPos2 = None
self.ax.grid(True)
if groundTruth != None:
grnd = groundTruth.toArray(False)
self.groundPlot, = self.ax.plot (grnd[:,0], grnd[:,1])
# This must be done after all initial drawing
self.canvas.draw()
self.bg = self.canvas.copy_from_bbox (self.ax.bbox)
# Bind events to timer function
wx.EVT_TIMER (self, TIMER_ID, self.onTimer)
def onTimer (self, event):
self.canvas.restore_region(self.bg)
orbPosition1 = orbProc1.getPose()
if orbPosition1 is not None:
if self.orbPos1 is None:
self.orbPos1 = self.ax.scatter (orbPosition1.x, orbPosition1.y, color=[[1,0,0,0.5]], s=100, linewidths=0)
else :
self.orbPos1.set_offsets([orbPosition1.x, orbPosition1.y])
orbPosition2 = orbProc2.getPose()
if orbPosition2 is not None:
if self.orbPos2 is None:
self.orbPos2 = self.ax.scatter (orbPosition2.x, orbPosition2.y, color=[[0,1,0,0.5]], s=100, linewidths=0)
else :
self.orbPos2.set_offsets([orbPosition2.x, orbPosition2.y])
self.canvas.draw()
self.canvas.blit(self.ax.bbox)
示例5: PlotFigure
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
class PlotFigure(wx.Frame):
"""Matplotlib wxFrame with animation effect"""
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, title="CPU Usage Monitor", size=(600, 400))
self.fig = Figure((6, 4), 100)
self.canvas = FigureCanvas(self, wx.ID_ANY, self.fig)
self.ax = self.fig.add_subplot(111)
# limit the X and Y axes dimensions
self.ax.set_ylim(2140, 2150)
self.ax.set_xlim([0, POINTS])
self.ax.set_autoscale_on(False)
self.ax.set_xticks([])
# we want a tick every 10 point on Y (101 is to have 10
#self.ax.set_yticks(range(0, 101, 10))
self.ax.grid(True)
self.user = [None] * POINTS
self.l_user,=self.ax.plot(range(POINTS),self.user,label=u'IF1406')
self.md = MdThread("127.0.0.1",12345)
self.md.start()
self.md.RegTick(self.OnTick)
# add the legend
self.ax.legend(loc='upper center',
ncol=4,
prop=font_manager.FontProperties(size=10))
self.canvas.draw()
self.bg = self.canvas.copy_from_bbox(self.ax.bbox)
#wx.EVT_TIMER(self, TIMER_ID, self.onTimer)
def OnTick(self,tick):
self.canvas.restore_region(self.bg)
# update the data
if tick.InstrumentID != 'IF1404':
return
print tick.LastPrice
temp =np.random.randint(10,80)
self.user = self.user[1:] + [tick.LastPrice]
# update the plot
self.l_user.set_ydata(self.user)
# just draw the "animated" objects
self.ax.draw_artist(self.l_user)# It is used to efficiently update Axes data (axis ticks, labels, etc are not updated)
self.canvas.blit(self.ax.bbox)
示例6: PlotPanel
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
class PlotPanel(wx.Panel):
def __init__(self,parent,data_window,yrange=(-3,3),**kwargs):
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.figure import Figure
self.dw = data_window
# initialize Panel
if 'style' not in kwargs.keys():
kwargs['style'] = wx.NO_FULL_REPAINT_ON_RESIZE
wx.Panel.__init__( self, parent, **kwargs )
# initialize matplotlib stuff
self.figure = Figure()
self.canvas = FigureCanvasWxAgg(self, -1, self.figure )
self.subplot_x = self.figure.add_subplot(311)
self.subplot_x.set_ylim(yrange)
self.subplot_x.set_xticks([])
self.subplot_y = self.figure.add_subplot(312)
self.subplot_y.set_ylim(yrange)
self.subplot_y.set_xticks([])
self.subplot_z = self.figure.add_subplot(313)
self.subplot_z.set_ylim(yrange)
self.subplot_z.set_xticks([])
self.dw.winlock.acquire()
self.line_x, = self.subplot_x.plot(self.dw.win[:,0],color='r',lw=2,animated=True)
self.line_y, = self.subplot_y.plot(self.dw.win[:,1],color='g',lw=2,animated=True)
self.line_z, = self.subplot_z.plot(self.dw.win[:,2],color='b',lw=2,animated=True)
self.dw.winlock.release()
self.canvas.draw()
self.draw()
self.dw.start()
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER,self.OnTimer,self.timer)
self.timer.Start(1)
def OnTimer(self,event):
self.draw()
def draw( self ):
"""Draw data."""
if not hasattr(self, 'background' ):
self.background = self.canvas.copy_from_bbox(self.figure.bbox)
self.canvas.restore_region(self.background)
self.dw.winlock.acquire()
self.line_x.set_ydata(self.dw.win[:,0])
self.line_y.set_ydata(self.dw.win[:,1])
self.line_z.set_ydata(self.dw.win[:,2])
self.dw.winlock.release()
self.subplot_x.draw_artist(self.line_x)
self.subplot_y.draw_artist(self.line_y)
self.subplot_z.draw_artist(self.line_z)
self.canvas.blit(self.subplot_x.bbox)
self.canvas.blit(self.subplot_y.bbox)
self.canvas.blit(self.subplot_z.bbox)
示例7: PanelGraph
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
#.........这里部分代码省略.........
def set_plot(self, spectrum, isLimited, limit, extent, annotate=False):
if spectrum is not None and extent is not None:
if isLimited is not None and limit is not None:
self.spectrum = copy.copy(spectrum)
self.extent = extent
self.annotate = annotate
self.isLimited = isLimited
self.limit = limit
if self.plot.get_plot_thread() is None:
self.timer.Stop()
self.measureTable.set_selected(self.spectrum, self.selectStart,
self.selectEnd)
if isLimited:
spectrum = reduce_points(spectrum, limit)
self.plot.set_plot(self.spectrum, self.extent, annotate)
else:
self.timer.Start(200, oneShot=True)
def set_plot_title(self):
if len(self.settings.devices) > 0:
gain = self.settings.devices[self.settings.index].gain
else:
gain = 0
self.figure.suptitle("Frequency Spectrogram\n{0} - {1} MHz,"
" gain = {2}dB".format(self.settings.start,
self.settings.stop, gain))
def redraw_plot(self):
if self.spectrum is not None:
self.set_plot(self.spectrum,
self.settings.pointsLimit,
self.settings.pointsMax,
self.extent, self.settings.annotate)
def set_grid(self, on):
self.plot.set_grid(on)
def draw_overlay(self):
if self.background is not None:
self.canvas.restore_region(self.background)
self.draw_select()
self.draw_measure()
self.canvas.blit(self.plot.get_axes().bbox)
def draw_select(self):
if self.selectStart is not None and self.selectEnd is not None:
self.mouseSelect.draw(self.selectStart, self.selectEnd)
def hide_overlay(self):
if self.plot is not None:
self.plot.hide_measure()
self.hide_select()
def hide_measure(self):
if self.plot is not None:
self.plot.hide_measure()
def hide_select(self):
if self.mouseSelect is not None:
self.mouseSelect.hide()
def draw_measure(self):
if self.measure is not None and self.measure.is_valid():
self.plot.draw_measure(self.measure, self.show)
def update_measure(self, measure, show):
self.measure = measure
self.show = show
self.draw_overlay()
def get_figure(self):
return self.figure
def get_axes(self):
return self.plot.get_axes()
def get_canvas(self):
return self.canvas
def get_toolbar(self):
return self.toolbar
def scale_plot(self, force=False):
self.plot.scale_plot(force)
def clear_plots(self):
self.plot.clear_plots()
def clear_selection(self):
self.measure = None
self.measureTable.clear_measurement()
self.selectStart = None
self.selectEnd = None
self.mouseSelect.clear()
self.enable_menu(False)
def close(self):
close_modeless()
示例8: MyPlot
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
class MyPlot(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self,parent, -1)
self.fig = None
self.canvas = None
self.ax = None
self.background = None
self.lines = []
self._doRePlot = True
self.foo = 1
self.t = time.time()
self.blit_time=0
self.y = numpy.cos(numpy.arange(0.0,1.0,0.1))
self.ylim = None
self.autolim = None
self.span = 500
self.begin = 0
self.channels = []
self._SetSize()
self.Bind(wx.EVT_IDLE, self._onIdle)
self.Bind(wx.EVT_SIZE, self._onSize)
self._resizeFlag = True
sizer=wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.canvas,1,wx.GROW)
self.SetSizer(sizer)
self.canvas.Show()
def addChannel(self, channel):
self.channels.append(channel)
def setTimespan(self, span):
self.span = span
def setYlim(self, ymin, ymax):
self.ylim = [ymin, ymax]
def _resizeCreateContent(self):
'''Resize graph according to user input and initialize plots'''
self.lines=[]
for c in self.channels:
data=c.getNext()
line, = self.ax.plot(data[0],data[1], animated = True)
self.lines.append(line)
gca = self.fig.gca()
#TODO: add an auto mode here
if self.ylim:
gca.set_ylim(self.ylim)
else:
if self.autolim:
diff = self.autolim[1] - self.autolim[0]
gca.set_ylim([self.autolim[0] - 0.1*diff, self.autolim[1] + 0.1*diff])
else:
gca.set_ylim([-1,1])
gca.set_xlim([self.begin, (self.begin+self.span)])
self.ax.grid()
#self.fig.clear()
self.canvas.draw()
self.background = None
print 'content'
self._doRePlot = False
def _createGraphics(self):
"""Reallocate new figure and take care of panel resizing issues"""
self.fig=Figure()
self.canvas=FigureCanvas(self,-1,self.fig)
self.ax = self.fig.add_subplot(111)
self.ax._cachedRenderer=self.canvas.get_renderer()
def _onSize(self, evt):
self._resizeFlag = True
def _onIdle(self, event):
event.RequestMore(True)
if self._resizeFlag:
self._resizeFlag = False
self._SetSize()
self.draw_plot()
#if self.foo > 2000:
#u=time.time()
#print self.foo/(u-self.t), self.blit_time/(u-self.t)
#exit(0)
def _SetSize(self, pixels=None):
if not pixels:
pixels = self.GetClientSize()
self._createGraphics()
self.canvas.SetSize(pixels)
self.fig.set_size_inches(pixels[0]/self.fig.get_dpi(),
#.........这里部分代码省略.........
示例9: PlotPanel
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
class PlotPanel(wx.Panel):
def __init__(self, *args, **kwds):
# begin wxGlade: PlotPanel.__init__
uc = kwds.pop('uc')
kwds["style"] = wx.DOUBLE_BORDER|wx.TAB_TRAVERSAL
wx.Panel.__init__(self, *args, **kwds)
self.__set_properties()
self.__do_layout()
# end wxGlade
# ``PlotPanel`` size is (600, 400).
self.figure = Figure(figsize=(6, 4), dpi=100)
self.ax = self.figure.add_subplot(111)
self.canvas = FigureCanvas(self, wx.ID_ANY, self.figure)
#self.ax.set_ylim([0.0, 1023.0])
self.ax.set_ylim([0.0, 80.0])
self.ax.set_xlim([0.0, POINTS])
self.ax.set_autoscale_on(False) # Disable autoscale.
self.ax.set_xticks([])
self.ax.grid(True, animated=True, linewidth=1, antialiased=True,
fillstyle='full')
self.ax.set_title(u'Distance vs time')
self.ax.set_ylabel('distance (cm)')
self.ax.set_xlabel('time')
# Initial empty plot.
self.distance = [None] * POINTS
self.distance_plot, = self.ax.plot(range(POINTS), self.distance,
label='Distance')
self.canvas.draw()
# Save the clean background - everything but the line is drawn and
# saved in the pixel buffer background.
self.bg = self.canvas.copy_from_bbox(self.ax.bbox)
# Represents UC interfaced through the serial port.
self.uc = uc
assert self.uc.port.isOpen()
assert self.uc.status == OK_STATUS
self.uc.set_mode(SERIAL_MODE)
# Take a snapshot of voltage, needed for the update algorithm.
self.before = self.uc.distance
wx.EVT_TIMER(self, TIMER_ID, self.onTimer)
# Initialize the timer.
self.t = wx.Timer(self, TIMER_ID)
self.samples = 0
def __set_properties(self):
# begin wxGlade: PlotPanel.__set_properties
self.SetMinSize((600, 400))
self.SetToolTipString("Distance plot.")
# end wxGlade
def __do_layout(self):
# begin wxGlade: PlotPanel.__do_layout
pass
# end wxGlade
def onTimer(self, evt):
# Get distance.
distance = self.uc.distance
if distance <= 80.0:
distance_str = str(distance)
else:
distance = 80.0
distance_str = u"OUT OF RANGE"
mainframe.distance_label.SetLabel(distance_str)
self.samples += 1
# Restore the clean background, saved at the beginning.
self.canvas.restore_region(self.bg)
# Update data array.
self.distance = self.distance[1:] + [distance]
# Update plot.
self.distance_plot.set_ydata(self.distance)
# Just draw the "animated" objects.
self.ax.draw_artist(self.distance_plot)
# Blit the background with the animated lines.
self.canvas.blit(self.ax.bbox)
with open(LOG_FILE_PATH, 'a+') as f:
f.write("{0},{1}\n".format(str(self.samples * TIME_DELTA),
str(distance)))
示例10: PlotFrame
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
#.........这里部分代码省略.........
# Not sure how to properly add a colorbar
# self.cb = self.fig.colorbar(self.im, orientation='vertical')
# refresh the canvas
self.canvas.draw()
def get_xyt_data(self):
# Create scaled (0-1) luminance(x,y) array from ascii G-2 disk_out file
# get the data to plot from the specified filename
# Note that NumPy loadtxt transparently deals with bz2 compression
self.SetStatusText('Data loading - please wait ....')
rawdata = np.loadtxt(self.filename)
# Note the difference between NumPy [row, col] order and network
# x-y grid (x, y) = (col, row). We want a NumPy NY x NX, not
# NX x NY, array to be used by the AxesImage object.
xydata = np.resize(rawdata, (self.Ntimes, self.NY, self.NX))
# imshow expects the data to be scaled to range 0-1.
Vmin = xydata.min()
Vmax = xydata.max()
self.ldata = (xydata - Vmin)/(Vmax - Vmin)
self.data_loaded = True
self.SetStatusText('Data has been loaded - click Play')
def plot_data(self):
''' plot_data() shows successive frames of the data that was loaded
into the ldata array. Creating a new self.im AxesImage instance
for each frame is extremely slow, so the set_data method of
AxesImage is used to load new data into the existing self.im for
each frame. Normally 'self.canvas.draw()' would be used to
display a frame, but redrawing the entire canvas, redraws the
axes, labels, sliders, buttons, or anything else on the canvas.
This uses a method taken from an example in Ch 7, p. 192
Matplotlib for Python developers, with draw_artist() and blit()
redraw only the part that was changed.
'''
if self.data_loaded == False:
# bring up a warning dialog
msg = """
Data for plotting has not been loaded!
Please enter the file to plot with File/Open, unless
it was already specified, and then click on 'New Data'
to load the data to play back, before clicking 'Play'.
"""
wx.MessageBox(msg, "Plot Warning", wx.OK | wx.ICON_ERROR,self)
return
# set color limits
self.im.set_clim(0.0, 1.0)
self.im.set_interpolation('nearest')
# 'None' is is slightly faster, but not implemented for MPL ver < 1.1
# self.im.set_interpolation('None')
# do an initial draw, then save the empty figure axes
self.canvas.draw()
# self.bg = self.canvas.copy_from_bbox(self.axes.bbox)
# However the save and restore is only needed if I change
# axes legends, etc. The draw_artist(artist), and blit
# are much faster than canvas.draw() and are sufficient.
print 'system time (seconds) = ', time.time()
# round frame_min down and frame_max up for the time window
frame_min = int(self.t_min/self.dt)
示例11: PlotFigure
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
#.........这里部分代码省略.........
self.average.set_position([0.08, 0.05, 0.85, 0.28])
self.canvas.draw()
# save the clean background
self.background_1st = self.canvas.copy_from_bbox(self.ax.bbox)
self.background_2nd = self.canvas.copy_from_bbox(self.average.bbox)
self.global_timer_index = 0
self.local_timer_index = 0
self.power8_current_all_values = []
self.x86_current_all_values = []
wx.EVT_TIMER(self, TIMER_ID, self.on_timer)
def on_timer(self, event):
# restore the clean background, saved at the beginning
self.canvas.restore_region(self.background_1st)
self.canvas.restore_region(self.background_2nd)
#copyfile(power8_source_filename, power8_input_filename)
#copyfile(x86_source_filename, x86_input_filename)
#print(time.strftime("%s"))
self.global_timer_index += 1
self.local_timer_index += 1
line_index = self.global_timer_index - 1
less_number = EMPTY_NUMBER - self.local_timer_index
needed_number = self.local_timer_index - 1
# get the value of current index from file
power8_current_value = self.read_from_file_by_index(
power8_input_filename, line_index)
x86_current_value = self.read_from_file_by_index(
x86_input_filename, line_index)
# normal return: accumulate the return value directly.
# abnormal return: accumulate the previous one.
if power8_current_value:
self.power8_accumulate_value += power8_current_value
self.power8_previous_value = power8_current_value
else:
# TODO: new add for error character
power8_current_value = self.power8_previous_value
self.power8_accumulate_value += self.power8_previous_value
if x86_current_value:
self.x86_accumulate_value += x86_current_value
self.x86_previous_value = x86_current_value
else:
# TODO: new add for error character
x86_current_value = self.x86_previous_value
self.x86_accumulate_value += self.x86_previous_value
#print("==> accumulate = {0} and previous = {1} and current ="
# "{2}".format(self.power8_accumulate_value,
# self.power8_previous_value,
# power8_current_value))
# update the new data into 1st subplot
self.power8_current_all_values = \
self.power8_current_all_values[:needed_number] + \
[power8_current_value] + [None] * less_number
self.x86_current_all_values = \
self.x86_current_all_values[:needed_number] + \
[x86_current_value] + [None] * less_number
self.power8_plot.set_ydata(self.power8_current_all_values)
self.x86_plot.set_ydata(self.x86_current_all_values)
# update the new data into 2nd subplot
self.power8_ave_value = self.power8_accumulate_value / \
self.global_timer_index
self.x86_ave_value = self.x86_accumulate_value / \
self.global_timer_index
self.power8_barh.set_width(self.power8_ave_value)
self.x86_barh.set_width(self.x86_ave_value)
self.ax.draw_artist(self.power8_plot)
self.ax.draw_artist(self.x86_plot)
self.average.draw_artist(self.power8_barh)
self.average.draw_artist(self.x86_barh)
# clean the data on screen
if self.local_timer_index == EMPTY_NUMBER:
#print("local_timer_index is full")
self.power8_current_all_values = []
self.x86_current_all_values = []
self.local_timer_index = 0
self.canvas.blit(self.ax.bbox)
self.canvas.blit(self.average.bbox)
def read_from_file_by_index(self, filename, line_number):
try:
with open(filename, 'r') as file_object:
all_content = file_object.read().split('\n')[:-1]
file_length = len(all_content)
except IOError, e:
print("Error->[read_from_file_by_index]: CAN NOT find the"
"filename:[{0}]".format(filename))
except Exception as ex:
print("Error->[read_from_file_by_index]: {0}".format(str(ex)))
开发者ID:MingquanLiang,项目名称:oftenusedscript,代码行数:104,代码来源:display_TPCC-Performance_CP1_vs_X86_20151202_v2.py
示例12: CirclePanel
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
#.........这里部分代码省略.........
#update the title, which shows the equation of the circle
def UpdateTitle(self):
titleText = "$(x{h})^2 + (y{k})^2 = {r}^2$"
titleH, titleK, titleR = "-0.0", "-0.0", round(self.r, 2)
#format signs correctly
if self.h < 0.0:
titleH = "+{val}".format(val=abs(round(self.h, 2)))
elif self.h > 0.0:
titleH = "-{val}".format(val=abs(round(self.h, 2)))
if self.k < 0.0:
titleK = "+{val}".format(val=abs(round(self.k, 2)))
elif self.k > 0.0:
titleK = "-{val}".format(val=abs(round(self.k, 2)))
#show the students that they can omit h or k in the equation if it equals 0.0
if self.h == 0.0 and not self.k == 0.0:
titleText = titleText + " OR $x^2 + (y{k})^2 = {r}^2$"
elif not self.h == 0.0 and self.k == 0.0:
titleText = titleText + " OR $(x{h})^2 + y^2 = {r}^2$"
elif self.h == 0.0 and self.k == 0.0:
titleText = titleText + " OR $x^2 + y^2 = {r}^2$"
self.subplot.set_title(titleText.format(h=titleH, k=titleK, r=titleR),
fontproperties=mpl.font_manager.FontProperties(size="x-large"))
#draw/redraw the canvas
def DrawFigure(self):
self.subplot.clear()
#set the "window" of the plot
self.subplot.set_ylim([-5, 5])
self.subplot.set_xlim([-5, 5])
#draw grid and axes lines
self.subplot.grid(True)
self.subplot.axhspan(0, 0)
self.subplot.axvspan(0, 0)
self.UpdateTitle()
#draw the circles
circleColor = (0, 0, 1, 1)
#must multiply r by 2 b/c Arc takes the length (diameter) of the axes, not the radius
#circle1 is the reference circle (red)
"""
circle1 = patches.Arc((0, 0), 2, 2, edgecolor="#FF0000", alpha=0.8)
self.subplot.plot([0.0, 1.0], [0.0, 0.0], marker="o", color="#FF0000", mec="#FF0000", mfc="#FF0000")
self.subplot.add_patch(circle1)
"""
#circle2 is the user-manipulated circle (blue)
self.circle = patches.Arc((self.h, self.k), self.r*2, self.r*2, edgecolor=circleColor, alpha=0.8)
self.points = self.subplot.plot([self.h, self.h+self.r], [self.k, self.k], marker="o", picker=5, color=circleColor, mec=circleColor, mfc=circleColor)
#get the first (and only) line, not the list
self.points = self.points[0]
self.subplot.add_patch(self.circle)
self.canvas.draw()
def UpdateFigure(self):
#update data
self.circle.center = (self.h, self.k)
self.circle.width = 2*self.r
self.circle.height = 2*self.r
self.points.set_xdata([self.h, self.h+self.r])
self.points.set_ydata([self.k, self.k])
self.UpdateTitle()
#draw
self.canvas.restore_region(self.background)
self.subplot.draw_artist(self.subplot.title)
self.subplot.draw_artist(self.circle)
self.subplot.draw_artist(self.points)
self.canvas.blit(self.figure.bbox)
def SaveBackground(self):
self.circle.set_animated(True)
self.points.set_animated(True)
#clear plot
self.subplot.set_title(" ")
self.canvas.draw()
#save figure
self.background = self.canvas.copy_from_bbox(self.figure.bbox)
self.UpdateTitle()
#blit figures back onto the plot
self.subplot.draw_artist(self.circle)
self.subplot.draw_artist(self.points)
self.subplot.draw_artist(self.subplot.title)
self.canvas.blit(self.figure.bbox)
def SetParameters(self, h, k, r):
self.h = h
self.k = k
self.r = r
示例13: NaoPanel
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
#.........这里部分代码省略.........
self.naohistoryx = list()
self.naohistoryy = list()
self.positionmeasurementplot = self.axes.plot([0,0],[0,0], 'blue', marker='o', markersize=5, linewidth=0, markeredgewidth=0, animated=True)
self.orientationmeasurementplot = self.axes.plot([0,0],[0,0], 'blue', linewidth=2, animated=True)
self.shapeplot = self.axes.plot([0,0],[0,0], 'blue', marker='o', markersize=2, linewidth=0, markeredgewidth=0, animated=True)
self.estimateplot = self.axes.plot([0,0],[0,0], 'red', linewidth=2, animated=True)
self.particleplot = self.axes.quiver([0,0],[0,0], [1,1], [0.5, -0.5], [1, 1], cmap=pylab.gray(), animated=True)
##plot formatting
self.axes.set_title('Nao Image', fontsize='10')
self.axes.set_xlabel('y (cm)', fontsize='10')
self.axes.set_ylabel('x (cm)', fontsize='10')
ticks = numpy.arange(-25, 25 + 5, 5)
labels = [str(tick) for tick in ticks]
self.axes.set_yticks(ticks)
self.axes.set_yticklabels(labels, fontsize=8)
self.axes.set_ylim(ticks[0], ticks[-1])
ticks = -numpy.arange(-50, 50+5, 5)
labels = [str(tick) for tick in ticks]
self.axes.set_xticks(ticks)
self.axes.set_xticklabels(labels,fontsize=8)
self.axes.set_xlim(ticks[0], ticks[-1])
self.canvas.draw()
self.canvas.gui_repaint()
# save the clean slate background -- everything but the animated line
# is drawn and saved in the pixel buffer background
self.background = self.canvas.copy_from_bbox(self.axes.bbox)
#self.leftedgeplot = self.axes.plot([0,0],[0,0], 'orange', marker='o', markersize=4, linewidth=0, animated=True)
#self.rightedgeplot = self.axes.plot([0,0],[0,0], 'purple', marker='o', markersize=4, linewidth=0, animated=True)
def setNaoFinder(self, finder):
""" """
self.NAOFinder = finder
def setLocalisation(self, localisation):
""" """
self.Localisation = localisation
def updateData(self, data):
"""updateData. Updates the data that this panel is displaying.
"""
# Note the x values are plotted on the y-axis, and the y values are plotted on the x-axis
naox = self.Localisation.X
naoy = self.Localisation.Y
naoorientation = self.Localisation.Orientation
measurednaox = self.NAOFinder.NaoX
measurednaoy = self.NAOFinder.NaoY
measurednaoorientation = self.NAOFinder.NaoOrientation
self.positionmeasurementplot[0].set_data([measurednaoy, measurednaoy], [measurednaox, measurednaox])
self.orientationmeasurementplot[0].set_data([measurednaoy + 10*numpy.sin(measurednaoorientation - numpy.pi), measurednaoy + 10*numpy.sin(measurednaoorientation)], [measurednaox + 10*numpy.cos(measurednaoorientation - numpy.pi), measurednaox + 10*numpy.cos(measurednaoorientation)])
self.shapeplot[0].set_data(self.NAOFinder.ShapeY, self.NAOFinder.ShapeX)
self.naohistoryx.append(naox)
self.naohistoryy.append(naoy)
if len(self.naohistoryx) > 20:
del self.naohistoryx[0]
del self.naohistoryy[0]
self.naohistoryplot[0].set_data(self.naohistoryy, self.naohistoryx)
self.estimateplot[0].set_data([naoy, naoy + 10*numpy.sin(self.Localisation.Orientation)], [naox, naox + 10*numpy.cos(self.Localisation.Orientation)])
#self.particleplot = self.axes.quiver(numpy.array(self.Localisation.States[:,Localisation.Y]), numpy.array(self.Localisation.States[:,Localisation.X]), -numpy.sin(self.Localisation.States[:,Localisation.THETA]), numpy.cos(self.Localisation.States[:,Localisation.THETA]), 1.0 - self.Localisation.GUIWeights, headlength=10, headwidth=10, width=0.001, scale=50.0)
self.axes.set_xlim(naoy + 50, naoy - 50)
self.axes.set_ylim(naox - 25, naox + 25)
# restore the clean slate background
self.canvas.restore_region(self.background)
# just draw the animated artist
self.axes.draw_artist(self.shapeplot[0])
#self.axes.draw_artist(self.particleplot)
self.axes.draw_artist(self.naohistoryplot[0])
self.axes.draw_artist(self.orientationmeasurementplot[0])
self.axes.draw_artist(self.positionmeasurementplot[0])
self.axes.draw_artist(self.estimateplot[0])
# just redraw the axes rectangle
self.canvas.blit(self.axes.bbox)
#leftx = list()
#lefty = list()
#for leftedge in self.NAOFinder.LeftEdges:
# leftx.append(data[0][leftedge])
# lefty.append(data[1][leftedge])
#rightx = list()
#righty = list()
#for rightedge in self.NAOFinder.RightEdges:
# rightx.append(data[0][rightedge])
# righty.append(data[1][rightedge])
#self.leftedgeplot[0].set_data(lefty, leftx)
#self.rightedgeplot[0].set_data(righty, rightx)
def OnNaoPanelPaint(self, event):
pass
示例14: Graph
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
#.........这里部分代码省略.........
self.sub_plots.set_default_formatter(formatter, axes)
# redraw screen
self.canvas.draw()
def set_label(self, xlabel='', ylabel='', index = None):
"""
Set labels of the specified plot axes
keyword arguments:
xlabel -- (optional) sets the label of the x-axis (default: '')
ylabel -- (optional) sets the label of the y-axis (default: '')
index -- (optional) a integer or list of integers with the index of
sub-plots for which a the labels should be set. When 'None' the
labels is set for all sub-plots (default: None)
"""
if type(index) == list:
for i in index:
self.sub_plots.set_label(xlabel, ylabel, i)
elif type(index) == int:
self.sub_plots.set_label(xlabel, ylabel, index)
else:
# do all
count = self.layout[-1]
for i in range(count):
self.sub_plots.set_label(xlabel, ylabel, i)
# Redraw screen
self.canvas.draw()
def set_limits(self, limits, index = 0):
"""
Sets the axis limits of the specified sub-plot
keyword arguments:
limits -- A list to set the limits of x and y-axis: [x1, x2, y1, y2]
index -- (optional) index of subplot to set axis limits (default: 0)
"""
self.sub_plots(index).axes.axis(limits)
self.canvas.draw()
def set_title(self, titles = '', index = 0):
"""
Set titles of the sub-plots
keyword arguments:
titles -- should be a list of title strings or a single
string, in which case an index should be supplied (default: '')
index -- (optional) Is only needed when titles is a single string
specifies for which sub-plot to set the title
"""
if type(titles) == list:
for i, title in enumerate(titles):
self.sub_plots(i).set_title(title)
else:
self.sub_plots(index).set_title(titles)
self.canvas.draw()
def update(self):
"""
Will send a draw command to the canvas uppdating the graphs
"""
self.canvas.draw()
self.canvas.flush_events()
def update_plot_only(self, lines, index=0):
"""
Will redraw the background and plot lines only
keyword arguments:
lines -- a list of line objects for the plot
index -- (optional) index of subplot to set axis limits (default: 0)
"""
try:
plot = self.sub_plots(index)
except IndexError:
raise(IndexError,
"The sub-plot of index:{0:d} doesn't exist".format(index))
ax = plot.axes
#draw the background
ax.draw_artist(ax.patch)
#draw the lines
for line in lines:
ax.draw_artist(line)
#draw the x grid
for line in ax.get_xgridlines():
ax.draw_artist(line)
#draw the y grid
for line in ax.get_ygridlines():
ax.draw_artist(line)
#redraw display selectively
self.canvas.blit(ax.bbox)
#should flush_events be used a bunch of erros seem to occur on this?
#self.canvas.flush_events()
示例15: CartesianPanel
# 需要导入模块: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg [as 别名]
# 或者: from matplotlib.backends.backend_wxagg.FigureCanvasWxAgg import blit [as 别名]
#.........这里部分代码省略.........
##left : the left side of the subplots of the figure
## | right : the right side of the subplots of the figure
## | bottom : the bottom of the subplots of the figure
## | top : the top of the subplots of the figure
## | wspace : the amount of width reserved for blank space between subplots
## | hspace : the amount of height reserved for white space between subplots
## |
self.canvas = FigureCanvasWxAgg(self, -1, self.fig)
##now put everything in a sizer
sizer = wx.BoxSizer(wx.VERTICAL)
# This way of adding to sizer allows resizing
sizer.Add(self.canvas, 1, wx.LEFT|wx.TOP|wx.GROW)
self.SetSizer(sizer)
self.Fit()
##now finally create the actual plot
##self.axes = self.fig.add_subplot(111)
self.axes = self.fig.add_axes((0.16,0.08,0.90,0.85)) ##left,bottom,width,height
self.plot = self.axes.plot([0,0],[0,0], 'b', animated=True)
self.naohistoryplot = self.axes.plot([0,0],[0,0], 'r', animated=True)
self.naohistoryx = list()
self.naohistoryy = list()
self.naoplot = self.axes.plot([0,0],[0,0], 'r', marker='o', markersize=4, animated=True)
self.leftedgeplot = self.axes.plot([0,0],[0,0], 'orange', marker='o', markersize=4, linewidth=0, animated=True)
self.rightedgeplot = self.axes.plot([0,0],[0,0], 'purple', marker='o', markersize=4, linewidth=0, animated=True)
##plot formatting
self.axes.set_title('Laser Image', fontsize='10')
#self.axes.set_xlabel('y (cm)', fontsize='10')
#self.axes.set_ylabel('x (cm)', fontsize='10')
ticks = numpy.arange(-450, 450+100, 100)
labels = [str(tick) for tick in ticks]
self.axes.set_yticks(ticks)
self.axes.set_yticklabels(labels, fontsize=8)
self.axes.set_ylim(ticks[0], ticks[-1])
ticks = numpy.arange(0, 450+100, 100)
labels = [str(tick) for tick in ticks]
self.axes.set_xticks(ticks)
self.axes.set_xticklabels(labels,fontsize=8)
self.axes.set_xlim(ticks[0], ticks[-1])
self.canvas.draw()
self.canvas.gui_repaint()
# save the clean slate background -- everything but the animated line
# is drawn and saved in the pixel buffer background
self.background = self.canvas.copy_from_bbox(self.axes.bbox)
def setNaoFinder(self, finder):
""" """
self.NAOFinder = finder
def updateData(self, data, naox, naoy):
"""updateData. Updates the data that this panel is displaying.
"""
self.x = data[0]
self.y = data[1]
self.plot[0].set_data(self.x, self.y)
self.naoplot[0].set_data([naox,naox], [naoy, naoy])
self.naohistoryx.append(naox)
self.naohistoryy.append(naoy)
if len(self.naohistoryx) > 400:
del self.naohistoryx[0]
del self.naohistoryy[0]
self.naohistoryplot[0].set_data(self.naohistoryx, self.naohistoryy)
leftx = list()
lefty = list()
for leftedge in self.NAOFinder.LeftEdges:
leftx.append(data[0][leftedge])
lefty.append(data[1][leftedge])
rightx = list()
righty = list()
for rightedge in self.NAOFinder.RightEdges:
rightx.append(data[0][rightedge])
righty.append(data[1][rightedge])
self.leftedgeplot[0].set_data(leftx, lefty)
self.rightedgeplot[0].set_data(rightx, righty)
# restore the clean slate background
self.canvas.restore_region(self.background)
# just draw the animated artist
self.axes.draw_artist(self.plot[0])
self.axes.draw_artist(self.naoplot[0])
self.axes.draw_artist(self.naohistoryplot[0])
self.axes.draw_artist(self.leftedgeplot[0])
self.axes.draw_artist(self.rightedgeplot[0])
# just redraw the axes rectangle
self.canvas.blit(self.axes.bbox)
def OnCartesianPanelPaint(self, event):
pass