本文整理汇总了Python中matplotlib.backends.backend_agg.FigureCanvasAgg.draw方法的典型用法代码示例。如果您正苦于以下问题:Python FigureCanvasAgg.draw方法的具体用法?Python FigureCanvasAgg.draw怎么用?Python FigureCanvasAgg.draw使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.backends.backend_agg.FigureCanvasAgg
的用法示例。
在下文中一共展示了FigureCanvasAgg.draw方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: small_plot
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
def small_plot(data):
x, y, area, colors = data
fig = Figure(figsize=(3, 3), dpi=80)
axes = fig.add_axes([0.0, 0.0, 1.0, 1.0], alpha=1.0)
axes.set_frame_on(False)
axes.set_xticks([])
axes.set_yticks([])
# axes.set_xlim(5, 6)
# axes.set_ylim(5, 6)
axes.scatter(x, y, s=area, c=colors, alpha=0.5)
axes.set_xlim(4, 7)
axes.set_ylim(4, 7)
canvas = FigureCanvasAgg(fig)
canvas.draw()
# canvas = FigureCanvasQTAgg(fig)
# buf = canvas.tostring_rgb()
buf = fig.canvas.tostring_rgb()
ncols, nrows = fig.canvas.get_width_height()
img = np.fromstring(buf, dtype=np.uint8).reshape(nrows, ncols, 3)
return img
示例2: chart
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
def chart(self):
clf()
img_dpi=72
width=400
height=300
fig=figure(dpi=img_dpi, figsize=(width/img_dpi, height/img_dpi))
x=arange(0, 2*pi+0.1, 0.1)
sine=plot(x, sin(x))
legend(sine, "y=sin x", "upper right")
xlabel('x')
ylabel('y=sin x')
grid(True)
canvas = FigureCanvasAgg(fig)
canvas.draw()
size = (int(canvas.figure.get_figwidth())*img_dpi, int(canvas.figure.get_figheight())*img_dpi)
buf=canvas.tostring_rgb()
im=PILImage.fromstring('RGB', size, buf, 'raw', 'RGB', 0, 1)
imgdata=StringIO()
im.save(imgdata, 'PNG')
self.REQUEST.RESPONSE.setHeader('Pragma', 'no-cache')
self.REQUEST.RESPONSE.setHeader('Content-Type', 'image/png')
return imgdata.getvalue()
# <markdowncell>
# 2. Then create an external method in ZMI (e.g. Id -\> mplchart, module
# name -\> mpl, function name -\> chart).
#
# 3. Click the Test tab and you should see the sine plot.
#
# * * * * *
#
# CategoryCookbookMatplotlib
#
示例3: spec_plot
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
def spec_plot(x, y, img, file_name, figure_size=(10,5), transparent=False):
import matplotlib
import matplotlib.figure
import matplotlib.cm
from matplotlib.backends.backend_agg import FigureCanvasAgg
figure_size = None
F = first_moment_analysis(x,y)
fig = matplotlib.figure.Figure(figure_size, 144, linewidth=0,
facecolor="white")
if transparent :
self.figure.figurePatch.set_alpha(0.0)
canvas = FigureCanvasAgg(fig)
p = fig.add_subplot(211)
p.set_position([0.1,0.3,0.8,0.6])
p.plot(x, y, '-')
fm = F.as_trace()
p.plot(fm[0],fm[1],"r-")
p.set_xlim(x[0],x[-1])
p.set_xlabel("position")
p.set_ylabel("intensity")
p.set_title("X-ray emission spectrum, first moment=%.2f"%(F.first_moment))
p2 = fig.add_subplot(212)
p2.set_position([0.1, 0.05, 0.8, 0.2])
im=p2.imshow(img.as_numpy_array(), cmap='spectral')
im.set_interpolation("none")
position=fig.add_axes([0.91,0.1,0.015,0.35])
# p2.imshow(img.as_numpy_array(), cmap=matplotlib.cm.gist_yarg)
p3=fig.colorbar(im, orientation='vertical', cax=position)
# p2.set_position([0.1, 0.05, 0.8, 0.2])
canvas.draw()
fig.savefig(file_name, dpi=200, format="png")
示例4: getAllRegionHepSpecsPieChart
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
def getAllRegionHepSpecsPieChart(request):
#totalRegionsHepSpecs = Zone.objects.all().aggregate(total_hepSpecs=Sum('hepspecs'))
totalRegionHepSpecs = sum([zn.hepspectotal() for zn in Zone.objects.all()])
if (totalRegionHepSpecs == None):
totalRegionHepSpecs = 0
#totalAllocatedHepSpecs = TopLevelAllocationByZone.objects.all().extra(select = {'total': 'SUM((hepspec_fraction * zone.hepspecs)/100)'}).values('hepspec_fraction', 'zone__hepspecs', 'total')
topLevelAllocationObjects = TopLevelAllocation.objects.all().values('hepspec')
totalAllocHepSpecs = 0.0
for oneObject in topLevelAllocationObjects:
if (oneObject['hepspec'] != None):
totalAllocHepSpecs = totalAllocHepSpecs + oneObject['hepspec']
fig = Figure(figsize=(4,4))
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
labels = []
fracs = []
allotedPer = 0
if totalRegionHepSpecs > 0:
allotedPer = (totalAllocHepSpecs/totalRegionHepSpecs) * 100
freePer = 100 - allotedPer
labels.append('Free')
fracs.append(freePer)
if allotedPer > 0:
labels.append('Allocated')
fracs.append(allotedPer)
patches, texts, autotexts = ax.pie(fracs, explode=None, labels=labels, colors=('g', 'r', 'c', 'm', 'y', 'k', 'w', 'b'), autopct='%.2f%%', pctdistance=0.4, labeldistance=1.1, shadow=False)
ax.set_title('\n Total Hepspec Allocation - All Regions \n Total: ' + str(round(totalRegionHepSpecs, 3)), fontdict=None, verticalalignment='bottom')
ax.grid(True)
#fig.canvas.mpl_connect('button_press_event', onclick)
response=HttpResponse(content_type='image/png')
canvas.print_png(response)
canvas.draw()
return response
示例5: show
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
def show(self):
self.figure.tight_layout()
FigureCanvasAgg.draw(self)
if PORT is None:
return
if matplotlib.__version__ < '1.2':
buffer = self.tostring_rgb(0, 0)
else:
buffer = self.tostring_rgb()
if len(set(buffer)) <= 1:
# do not plot empty
return
render = self.get_renderer()
width = int(render.width)
plot_index = index if os.getenv("PYCHARM_MATPLOTLIB_INTERACTIVE", False) else -1
try:
sock = socket.socket()
sock.connect((HOST, PORT))
sock.send(struct.pack('>i', width))
sock.send(struct.pack('>i', plot_index))
sock.send(struct.pack('>i', len(buffer)))
sock.send(buffer)
except OSError as _:
# nothing bad. It just means, that our tool window doesn't run yet
pass
示例6: getZoneHepSpecsPieChart
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
def getZoneHepSpecsPieChart(request):
regionName = request.REQUEST.get("regionname", "")
zoneName = request.REQUEST.get("zonename", "")
totalZoneHepSpecs = Zone.objects.get(name=zoneName, region__name=regionName)
if totalZoneHepSpecs.hepspecs == None:
totalZoneHepSpecs.hepspecs = 0
else:
totalZoneHepSpecs.hepspecs = totalZoneHepSpecs.hepspectotal()
topLevelAllocationByZoneObjects = TopLevelAllocationByZone.objects.filter(zone__name=zoneName, zone__region__name=regionName).values('hepspec_fraction', 'zone__hepspecs')
totalAllocHepSpecs = 0.0
for oneObject in topLevelAllocationByZoneObjects:
if ( (oneObject['hepspec_fraction'] != None) and (oneObject['zone__hepspecs'] != None) ):
totalAllocHepSpecs = totalAllocHepSpecs + ((oneObject['hepspec_fraction'] * oneObject['zone__hepspecs'])/100)
fig = Figure(figsize=(4,4))
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
labels = []
fracs = []
allotedPer = 0
if (totalZoneHepSpecs.hepspecs) > 0:
allotedPer = (totalAllocHepSpecs/totalZoneHepSpecs.hepspecs) * 100
freePer = 100 - allotedPer
labels.append('Free')
fracs.append(freePer)
if (allotedPer > 0):
labels.append('Allocated')
fracs.append(allotedPer)
patches, texts, autotexts = ax.pie(fracs, explode=None, labels=labels, colors=('g', 'r', 'c', 'm', 'y', 'k', 'w', 'b'), autopct='%.2f%%', pctdistance=0.4, labeldistance=1.1, shadow=False)
ax.set_title('\n Hepspec Allocation - Zone - ' + zoneName + '\n Region: ' + regionName + '(Total: ' + str(round(totalZoneHepSpecs.hepspecs, 3)) + ')', fontdict=None, verticalalignment='bottom')
ax.grid(True)
response=HttpResponse(content_type='image/png')
canvas.print_png(response)
canvas.draw()
return response
示例7: __init__
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
class HistogramMonitor:
def __init__(self, control):
self.control = control
print('Initing graph..')
self.fig = plt.figure()
self.ax = self.fig.add_subplot(1, 1, 1)
self.canvas = FigureCanvas(self.fig)
# Hold = False -> the new chart replaces the old
self.ax.hold(False)
#plt.ion() # start interactive mode to get the figure
self.ax.bar(range(256), [0]*256)
self.ax.set_xlabel('Brightness')
self.ax.set_ylabel('n')
self.canvas.print_figure('Histogram')
#time.sleep(1)
print('Graph drawn!')
def update(self):
newHistogram = self.control.getNewHistogram()
newError = self.control.getError()
# Update graph if the histogram has been updated
if newHistogram:
self.ax.bar(range(len(newHistogram)), newHistogram)
print("Plotted a new histogram")
else:
print("No new histogram available")
# Update title
#title = "Error: {0}".format(newError)
#self.ax.title = title
# Draw the changed plot
self.canvas.draw()
示例8: draw
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
def draw(self):
"""
Draw the figure using the agg renderer
"""
self.canvas.clear()
FigureCanvasAgg.draw(self)
if self.blitbox is None:
l, b, w, h = self.figure.bbox.bounds
w, h = int(w), int(h)
buf_rgba = self.get_renderer().buffer_rgba()
else:
bbox = self.blitbox
l, b, r, t = bbox.extents
w = int(r) - int(l)
h = int(t) - int(b)
t = int(b) + h
reg = self.copy_from_bbox(bbox)
buf_rgba = reg.to_string()
texture = Texture.create(size=(w, h))
texture.flip_vertical()
with self.canvas:
Color(1.0, 1.0, 1.0, 1.0)
self.img_rect = Rectangle(texture=texture, pos=self.pos, size=(w, h))
texture.blit_buffer(bytes(buf_rgba), colorfmt="rgba", bufferfmt="ubyte")
self.img_texture = texture
示例9: mpl_plot_ewma_embedded
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
def mpl_plot_ewma_embedded(figname, xs, ys, span):
# create the figure and axes for the plot
fig = Figure(figsize=(8, 6), dpi=75, facecolor=(1, 1, 1), edgecolor=(0, 0, 0))
ax = fig.add_subplot(111)
# calculate the moving average
ewma_ys = ewma(ys, span=span)
# plot the data
ax.plot(xs, ys, alpha=0.4, label="Raw")
ax.plot(xs, ewma_ys, label="EWMA")
ax.legend()
# write the figure to a temporary image file
filename = os.path.join(os.environ["TEMP"], "xlplot_%s.png" % figname)
canvas = FigureCanvas(fig)
canvas.draw()
canvas.print_png(filename)
# Show the figure in Excel as a Picture object on the same sheet
# the function is being called from.
xl = xl_app()
caller = xlfCaller()
sheet = xl.Range(caller.address).Worksheet
# if a picture with the same figname already exists then get the position
# and size from the old picture and delete it.
for old_picture in sheet.Pictures():
if old_picture.Name == figname:
height = old_picture.Height
width = old_picture.Width
top = old_picture.Top
left = old_picture.Left
old_picture.Delete()
break
else:
# otherwise place the picture below the calling cell.
top_left = sheet.Cells(caller.rect.last_row+2, caller.rect.last_col+1)
top = top_left.Top
left = top_left.Left
width, height = fig.bbox.bounds[2:]
# insert the picture
# Ref: http://msdn.microsoft.com/en-us/library/office/ff198302%28v=office.15%29.aspx
picture = sheet.Shapes.AddPicture(Filename=filename,
LinkToFile=0, # msoFalse
SaveWithDocument=-1, # msoTrue
Left=left,
Top=top,
Width=width,
Height=height)
# set the name of the new picture so we can find it next time
picture.Name = figname
# delete the temporary file
os.unlink(filename)
return "[Plotted '%s']" % figname
示例10: draw
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
def draw( self ):
"""
Draw the figure when xwindows is ready for the update
"""
if DEBUG: print "FigureCanvasQtAgg.draw", self
self.replot = True
FigureCanvasAgg.draw(self)
self.update()
示例11: export_close_figure
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
def export_close_figure(self, fobject):
"""
Export as a string and close the figure.
"""
canvas = FigureCanvasAgg(fobject)
canvas.draw()
size, buf = canvas.get_width_height(), canvas.tostring_rgb()
#close and return data
close()
return size, buf
示例12: draw
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
def draw(self):
"""
Draw the figure with Agg, and queue a request
for a Qt draw.
"""
# The Agg draw is done here; delaying it until the paintEvent
# causes problems with code that uses the result of the
# draw() to update plot elements.
FigureCanvasAgg.draw(self)
self.update()
示例13: paintEvent
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
def paintEvent( self, e ):
"""
Draw to the Agg backend and then copy the image to the qt.drawable.
In Qt, all drawing should be done inside of here when a widget is
shown onscreen.
"""
#FigureCanvasQT.paintEvent( self, e )
if DEBUG: print 'FigureCanvasQtAgg.paintEvent: ', self, \
self.get_width_height()
if self.replot:
FigureCanvasAgg.draw(self)
self.replot = False
if self.blitbox is None:
# matplotlib is in rgba byte order. QImage wants to put the bytes
# into argb format and is in a 4 byte unsigned int. Little endian
# system is LSB first and expects the bytes in reverse order
# (bgra).
if QtCore.QSysInfo.ByteOrder == QtCore.QSysInfo.LittleEndian:
stringBuffer = self.renderer._renderer.tostring_bgra()
else:
stringBuffer = self.renderer._renderer.tostring_argb()
qImage = QtGui.QImage(stringBuffer, self.renderer.width,
self.renderer.height,
QtGui.QImage.Format_ARGB32)
p = QtGui.QPainter(self)
p.drawPixmap(QtCore.QPoint(0, 0), QtGui.QPixmap.fromImage(qImage))
# draw the zoom rectangle to the QPainter
if self.drawRect:
# JB draw dashed white line on solid black to get contrast
p.setPen( QtGui.QPen( QtCore.Qt.black, 1, QtCore.Qt.SolidLine ) )
p.drawRect( self.rect[0], self.rect[1], self.rect[2], self.rect[3] )
p.setPen( QtGui.QPen( QtCore.Qt.white, 1, QtCore.Qt.DotLine ) )
p.drawRect( self.rect[0], self.rect[1], self.rect[2], self.rect[3] )
p.end()
else:
bbox = self.blitbox
l, b, r, t = bbox.extents
w = int(r) - int(l)
h = int(t) - int(b)
t = int(b) + h
reg = self.copy_from_bbox(bbox)
stringBuffer = reg.to_string_argb()
qImage = QtGui.QImage(stringBuffer, w, h, QtGui.QImage.Format_ARGB32)
pixmap = QtGui.QPixmap.fromImage(qImage)
p = QtGui.QPainter( self )
p.drawPixmap(QtCore.QPoint(l, self.renderer.height-t), pixmap)
p.end()
self.blitbox = None
self.drawRect = False
示例14: scatter2d
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
def scatter2d(X, y, fname):
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
f = Figure()
ax = f.add_subplot(111)
ax.scatter(X[:, 0], X[:, 1], c=y, s=2, edgecolors='none')
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
canvas = FigureCanvasAgg(f)
canvas.draw()
f.savefig(fname)
示例15: set_plot_state
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import draw [as 别名]
def set_plot_state(self, extra_high=False, extra_low=False):
"""
Build image state that wx.html understand
by plotting, putting it into wx.FileSystem image object
: extrap_high,extra_low: low/high extrapolations
are possible extra-plots
"""
# some imports
import wx
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg
# we use simple plot, not plotpanel
# make matlab figure
fig = plt.figure()
fig.set_facecolor('w')
graph = fig.add_subplot(111)
# data plot
graph.errorbar(self.data.x, self.data.y, yerr=self.data.dy, fmt='o')
# low Q extrapolation fit plot
if not extra_low == 'False':
graph.plot(self.theory_lowQ.x, self.theory_lowQ.y)
# high Q extrapolation fit plot
if not extra_high == 'False':
graph.plot(self.theory_highQ.x, self.theory_highQ.y)
graph.set_xscale("log", nonposx='clip')
graph.set_yscale("log", nonposy='clip')
graph.set_xlabel('$\\rm{Q}(\\AA^{-1})$', fontsize=12)
graph.set_ylabel('$\\rm{Intensity}(cm^{-1})$', fontsize=12)
canvas = FigureCanvasAgg(fig)
# actually make image
canvas.draw()
# make python.Image object
# size
w, h = canvas.get_width_height()
# convert to wx.Image
wximg = wx.EmptyImage(w, h)
# wxim.SetData(img.convert('RGB').tostring() )
wximg.SetData(canvas.tostring_rgb())
# get the dynamic image for the htmlwindow
wximgbmp = wx.BitmapFromImage(wximg)
# store the image in wx.FileSystem Object
wx.FileSystem.AddHandler(wx.MemoryFSHandler())
# use wx.MemoryFSHandler
self.imgRAM = wx.MemoryFSHandler()
# AddFile, image can be retrieved with 'memory:filename'
self.imgRAM.AddFile('img_inv.png', wximgbmp, wx.BITMAP_TYPE_PNG)
self.wximgbmp = 'memory:img_inv.png'
self.image = fig