本文整理汇总了Python中matplotlib.backends.backend_agg.FigureCanvasAgg.tostring_rgb方法的典型用法代码示例。如果您正苦于以下问题:Python FigureCanvasAgg.tostring_rgb方法的具体用法?Python FigureCanvasAgg.tostring_rgb怎么用?Python FigureCanvasAgg.tostring_rgb使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.backends.backend_agg.FigureCanvasAgg
的用法示例。
在下文中一共展示了FigureCanvasAgg.tostring_rgb方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_plot_topomap_interactive
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [as 别名]
def test_plot_topomap_interactive():
"""Test interactive topomap projection plotting."""
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
evoked = read_evokeds(evoked_fname, baseline=(None, 0))[0]
evoked.pick_types(meg='mag')
evoked.info['projs'] = []
assert not evoked.proj
evoked.add_proj(compute_proj_evoked(evoked, n_mag=1))
plt.close('all')
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.gca()
kwargs = dict(vmin=-240, vmax=240, times=[0.1], colorbar=False, axes=ax,
res=8, time_unit='s')
evoked.copy().plot_topomap(proj=False, **kwargs)
canvas.draw()
image_noproj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
assert len(plt.get_fignums()) == 1
ax.clear()
evoked.copy().plot_topomap(proj=True, **kwargs)
canvas.draw()
image_proj = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
assert not np.array_equal(image_noproj, image_proj)
assert len(plt.get_fignums()) == 1
ax.clear()
evoked.copy().plot_topomap(proj='interactive', **kwargs)
canvas.draw()
image_interactive = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')
assert_array_equal(image_noproj, image_interactive)
assert not np.array_equal(image_proj, image_interactive)
assert len(plt.get_fignums()) == 2
proj_fig = plt.figure(plt.get_fignums()[-1])
_fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data')
canvas.draw()
image_interactive_click = np.frombuffer(
canvas.tostring_rgb(), dtype='uint8')
assert_array_equal(image_proj, image_interactive_click)
assert not np.array_equal(image_noproj, image_interactive_click)
_fake_click(proj_fig, proj_fig.axes[0], [0.5, 0.5], xform='data')
canvas.draw()
image_interactive_click = np.frombuffer(
canvas.tostring_rgb(), dtype='uint8')
assert_array_equal(image_noproj, image_interactive_click)
assert not np.array_equal(image_proj, image_interactive_click)
示例2: chart
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [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: _fig_to_array
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [as 别名]
def _fig_to_array(self, fig):
"""
Convert matplotlib figure to an image (numpy array)
"""
fig.canvas.draw() # Updates
canvas = FigureCanvasAgg(fig)
buf = canvas.tostring_rgb()
w, h = canvas.get_width_height()
return np.fromstring(buf, dtype=np.uint8).reshape(h, w, 3)
示例4: export_close_figure
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [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
示例5: set_plot_state
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [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
示例6: mplfig_to_npimage
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [as 别名]
def mplfig_to_npimage(fig):
""" Converts a matplotlib figure to a RGB frame after updating the canvas"""
# only the Agg backend now supports the tostring_rgb function
from matplotlib.backends.backend_agg import FigureCanvasAgg
canvas = FigureCanvasAgg(fig)
canvas.draw() # update/draw the elements
# get the width and the height to resize the matrix
l,b,w,h = canvas.figure.bbox.bounds
w, h = int(w), int(h)
# exports the canvas to a string buffer and then to a numpy nd.array
buf = canvas.tostring_rgb()
image= np.fromstring(buf,dtype=np.uint8)
return image.reshape(h,w,3)
示例7: set_widget_value
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [as 别名]
def set_widget_value(cls,widget,x,vdb=None, addr=None):
out = StringIO()
img_dpi=72
width=400
height=300
f=pylab.figure(dpi=img_dpi, figsize=(width/img_dpi, height/img_dpi))
a=f.gca()
a.bar(range(len(x)),x,0.5)
out=StringIO()
canvas = FigureCanvasAgg(f)
canvas.draw()
size = (int(canvas.figure.get_figwidth())*img_dpi, int(canvas.figure.get_figheight())*img_dpi)
buf=canvas.tostring_rgb()
im=PIL.Image.fromstring('RGB', size, buf, 'raw', 'RGB', 0, 1)
x=PIL2NumPy(im)
widget.f(x)
示例8: _animate
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [as 别名]
def _animate(self, frames, func, **animArgs):
if self._outputParam is None: raise NotImplemented
images = []
figure = plt.Figure(figsize=(6,6), dpi=300, facecolor='w')
axes = figure.add_subplot(111)
canvas = FigureCanvasAgg(figure)
for frame in frames:
axes.clear()
func(frame, axes)
canvas.draw()
image = np.fromstring(canvas.tostring_rgb(), dtype=np.uint8)
image.shape = canvas.get_width_height() + (3,)
images.append(image)
self._render(images)
示例9: _animate
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [as 别名]
def _animate(self, frames, func, **animArgs):
if self._outputParam is None:
raise NotImplemented
figure = plt.Figure(figsize=(6, 6), dpi=300, facecolor="w")
axes = figure.add_subplot(111)
canvas = FigureCanvasAgg(figure)
chunks = 10
multiframes = [frames[i : i + chunks] for i in xrange(0, len(frames), chunks)]
count = 0
for frames in multiframes:
count += 1
images = []
for frame in frames:
axes.clear()
func(frame, axes)
canvas.draw()
image = np.fromstring(canvas.tostring_rgb(), dtype=np.uint8)
image.shape = canvas.get_width_height() + (3,)
images.append(image)
self._render(images, num=str(count))
if count > 1:
self._joinParts(count)
示例10: __init__
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [as 别名]
class Renderer:
def __init__(self):
self.size_x, self.size_y = SIZEX, SIZEY
self.my_dpi = 100
self.inches_sizex, self.inches_sizey = self.size_x/self.my_dpi, self.size_y/self.my_dpi
self.FLAG = 0
#Important parameters
self.loglikelihood = None
self.observedIm = None
self.currentIm = None
self.state = dict()
self.state['params'] = {'room_self.size_x':SIZEX, 'room_self.size_y':SIZEY}
self.state['blur'] = True
self.resolution = SIZEX*SIZEY
#pygame.init()
#self.screen = pygame.display.set_mode((SIZEX,SIZEY))
def loadImage(self,filename):
self.observedIm = pickle.load(open("demo.pkl","rb")) #Image.load('filename')
return 1
def getLogLikelihood(self,pflip):
compound = self.currentIm+self.observedIm
intersection_ones = len(np.where(compound == 2)[0])
intersection_zeros = len(np.where(compound == 0)[0])
intersection = intersection_zeros + intersection_ones
self.loglikelihood = intersection*log(1-pflip) + (self.resolution - intersection)*log(pflip)
return self.loglikelihood
""" works - funny
compound = self.currentIm+self.observedIm
union = len(np.where(compound >= 1)[0])
intersection = len(np.where(compound == 2)[0])
self.loglikelihood = 10*log(float(intersection+1)/union)
return self.loglikelihood"""
""" slow version
intersection = 0
union = 0
for ii in range(200):
for jj in range(200):
if self.observedIm[ii][jj] == 1 and self.currentIm[ii][jj] == 1:
intersection = intersection + 1
if self.observedIm[ii][jj] == 1 or self.currentIm[ii][jj] == 1:
union = union + 1
self.loglikelihood = log(float(intersection+1)/union)
return self.loglikelihood"""
def render_thing(self,thing):
self.f = Figure(frameon=False, dpi=self.my_dpi)
self.f.set_size_inches(self.inches_sizex, self.inches_sizey)
self.ax = Axes(self.f, [0., 0., 1., 1.])
self.ax.set_axis_off()
self.f.add_axes(self.ax)
self.canvas = FigureCanvasAgg(self.f)
self.ax.text(float(thing['left'])/self.state['params']['room_self.size_x'], float(thing['top'])/self.state['params']['room_self.size_y'], thing['id'], size = thing['size'])
self.canvas.draw()
im_str = self.canvas.tostring_rgb()
a = np.fromstring(im_str, dtype=np.uint8)
im = a.reshape(self.size_x, self.size_y, 3)
im = np.sum(im, 2)
im = np.float64(im)
im = im/np.max(im)
im = 1-im
if self.state['blur']:
bim = gaussian_filter(im, thing['blur_sigsq'], mode='wrap')
return bim
def get_rendered_image(self,things):
#print things
for i in range(len(things)):
bim = self.render_thing(things[i])
bim = npr.binomial(1, bim/np.max(bim))
if i == 0:
bim[bim.nonzero()] = 1
im = bim
else:
im[bim.nonzero()] = 1
self.currentIm = im
scipy.misc.imsave('all.jpg', im)
return im
def test(self):
self.state = dict()
self.state['params'] = {'room_self.size_x':SIZEX, 'room_self.size_y':SIZEY}
self.state['blur'] = True
#.........这里部分代码省略.........
示例11: __init__
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [as 别名]
class Renderer:
def __init__(self):
self.size_x = 3
self.size_y = 3
self.size_x, self.size_y = 300,300
my_dpi = 100
inches_sizex, inches_sizey = self.size_x/my_dpi, self.size_y/my_dpi
self.f = Figure(frameon=False, dpi=my_dpi)
self.f.set_size_inches(inches_sizex, inches_sizey)
self.ax = Axes(self.f, [0., 0., 1., 1.])
self.ax.set_axis_off()
self.f.add_axes(self.ax)
self.canvas = FigureCanvasAgg(self.f)
def render_thing(self,state,thing):
self.ax.text(float(thing['left'])/state['params']['room_self.size_x'], float(thing['top'])/state['params']['room_self.size_y'], thing['id'], size = thing['size'])
self.canvas.draw()
im_str = self.canvas.tostring_rgb()
a = np.fromstring(im_str, dtype=np.uint8)
im = a.reshape(self.size_x, self.size_y, 3)
im = np.sum(im, 2)
im = np.float64(im)
im = im/np.max(im)
im = 1-im
if state['blur']:
bim = gaussian_filter(im, thing['blur_sigsq'], mode='wrap')
return bim
def get_rendered_image(self,state,things):
for i in range(len(things)):
bim = self.render_thing(state,things[i])
bim = npr.binomial(1, bim/np.max(bim))
if i == 0:
bim[bim.nonzero()] = 1
im = bim
else:
im[bim.nonzero()] = 1
return im
def test(self):
state = dict()
state['params'] = {'room_self.size_x':300, 'room_self.size_y':300}
state['blur'] = True
things = []
things.append({'id':'A', 'size':50, 'left':100, 'top':100,'blur_sigsq':50})
things.append({'id':'Z', 'size':20, 'left':0, 'top':100,'blur_sigsq':10})
things.append({'id':'C', 'size':30, 'left':40, 'top':120,'blur_sigsq':0})
things.append({'id':'E', 'size':50, 'left':140, 'top':160,'blur_sigsq':3})
things.append({'id':'M', 'size':20, 'left':240, 'top':20,'blur_sigsq':0})
#t0 = time.time()
im = self.get_rendered_image(state,things)
#t1 = time.time()
#print t1-t0
imshow(im, cmap=cm.Greys)
show()
示例12: normpdf
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [as 别名]
# add a 'best fit' line
y = normpdf( bins, mu, sigma)
line, = ax.plot(bins, y, 'r--')
line.set_linewidth(1)
ax.set_xlabel('Smarts')
ax.set_ylabel('Probability')
ax.set_title(r'$\mathrm{Histogram of IQ: }\mu=100, \sigma=15$')
ax.set_xlim( (40, 160))
ax.set_ylim( (0, 0.03))
canvas.draw()
s = canvas.tostring_rgb() # save this and convert to bitmap as needed
# get the figure dimensions for creating bitmaps or numpy arrays,
# etc.
l,b,w,h = fig.bbox.bounds
w, h = int(w), int(h)
if 0:
# convert to a numpy array
X = numpy.fromstring(s, numpy.uint8)
X.shape = h, w, 3
if 0:
# pass off to PIL
import Image
im = Image.fromstring( "RGB", (w,h), s)
开发者ID:MariaNattestad,项目名称:clonal-deconvolution-from-copy-number,代码行数:32,代码来源:histogram_demo_canvasagg.py
示例13: make_png
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [as 别名]
def make_png(md5hash, cmap='gray', sigma=1.0, crop=False, options='', annotation=''):
"""Create a PNG stamp from a FITS file.
:param md5hash:
:param cmap:
:param sigma:
:param crop:
:param options:
:param annotation:
:return:
"""
outFile = md5hash
# Read
fitsim = maputils.FITSimage(outFile+'.fit')
fig = Figure(figsize=(5,5), facecolor="#ffffff")
canvas = FigureCanvas(fig)
frame = fig.add_subplot(1,1,1)
# Work out scaling
dat = fitsim.dat.ravel()
dat = dat.compress(dat>0.0)
if len(dat)>10:
z1, z2 = astats.zscale(dat, nsample=min(1000,len(dat)))
else:
z1 = z2 = 0.0
# Options
cmapinverse=False
if ('H' in options):
cmap='hot'
if ('W' in options):
cmap='winter'
if ('I' in options):
cmap=cmap+'_r'
annim = fitsim.Annotatedimage(frame, cmap=cmap.replace('_r',''), clipmin=z1, clipmax=z2*sigma)
if cmap.find('_r')>0:
annim.cmap.set_inverse(True)
annim.Image()
# Work out grid
a,d = fitsim.convproj.toworld(((0,0),(0,fitsim.hdr['NAXIS2'])))
b = numpy.array([5,10,15,20,25,30,35,40,45,50,55,60])
j = b.searchsorted(int(math.sqrt((a[0]-a[1])**2+(d[0]-d[1])**2)*3600.)/6)
deltay = b[j]
grat = annim.Graticule(
starty=fitsim.hdr['CRVAL2'], deltay=deltay/3600.,
startx=fitsim.hdr['CRVAL1'], deltax=deltay/3600./math.cos(math.radians(d[0])))
grat.setp_lineswcs0(visible=False)
grat.setp_lineswcs1(visible=False)
grat.setp_plotaxis(0, mode=0, label='')
grat.setp_plotaxis(1, mode=0, label='')
grat.setp_plotaxis(2, mode=0, label='')
grat.setp_plotaxis(3, mode=0, label='')
grat.setp_tick(visible=False)
grat.setp_tickmark(color='#99FF99', markersize=4, markeredgewidth=2)
# Plot center cross
xcen, ycen = fitsim.hdr['NAXIS1']/2.+0.5,fitsim.hdr['NAXIS2']/2.+0.5
frame.plot([xcen,xcen],[ycen/6.,ycen-ycen/6.],linewidth=1,color='#99FF99')
frame.plot([xcen,xcen],[ycen+ycen/6.,ycen*2-ycen/6.],linewidth=1,color='#99FF99')
frame.plot([xcen/6.,xcen-xcen/6.],[ycen,ycen],linewidth=1,color='#99FF99')
frame.plot([xcen+ycen/6.,xcen*2-ycen/6.],[ycen,ycen],linewidth=1,color='#99FF99')
annim.plot()
if (annotation):
frame.fill([0.001,0.999,0.999,0.001], [0.999,0.999,0.90-0.08, 0.90-0.08], transform = frame.transAxes, edgecolor='none', facecolor='#000000', alpha=0.4)
i = 0
for item in annotation.split('\\n'):
frame.text(0.04,0.92-i*0.06, item, transform = frame.transAxes, color='#FFFFFF')
i = i + 1
canvas.draw()
if crop:
size = canvas.get_renderer().get_canvas_width_height()
buf = canvas.tostring_rgb()
im = PILImage.fromstring('RGB', map(int, size), buf, 'raw', 'RGB', 0, 1)
im2 = im.convert('L'); im2 = PILImageOps.invert(im2)
im=im.crop(im2.getbbox())
im.save(outFile+'.png', 'PNG')
else:
s = StringIO.StringIO()
canvas.print_png(s)
s.flush()
s.seek(0)
open(outFile+'.png','w').write(s.read())
time.sleep(0.25)
示例14: render
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [as 别名]
def render(self):
try:
if self.data==None or len(self.data)==0: return
if self.xlimits==None or self.ylimits==None: return
except:
return
render = False
if self.needupd or not self.plotimg:
self.needupd=0
if self.main_display_list != 0:
glDeleteLists(self.main_display_list,1)
self.main_display_list = 0
if self.main_display_list == 0:
self.main_display_list = glGenLists(1)
glNewList(self.main_display_list,GL_COMPILE)
render = True
lighting = glIsEnabled(GL_LIGHTING)
glDisable(GL_LIGHTING)
EMShape.font_renderer=self.font_renderer # Important ! Each window has to have its own font_renderer. Only one context active at a time, so this is ok.
GL.glPushMatrix()
# overcome depth issues
glTranslate(0,0,5)
for k,s in self.shapes.items():
s.draw(self.scr2plot)
GL.glPopMatrix()
if render:
fig=Figure((self.width()/72.0,self.height()/72.0),dpi=72.0)
ax=fig.add_axes((.1,.1,.88,.88),autoscale_on=False,xlim=self.xlimits,ylim=self.ylimits,xscale=self.axisparms[2],yscale=self.axisparms[3])
#if self.axisparms[0] and len(self.axisparms[0])>0 : ax.set_xlabel(self.axisparms[0],size="xx-large")
#if self.axisparms[1] and len(self.axisparms[1])>0 : ax.set_ylabel(self.axisparms[1],size="xx-large")
ax.tick_params(axis='x', labelsize="x-large")
ax.tick_params(axis='y', labelsize="x-large")
canvas=FigureCanvasAgg(fig)
if self.inspector == None:
self.inspector = self.get_inspector()
#tostack = []
usedkeys = []
#colors = []
if self.alignment == "center":
histalign = "mid"
elif self.alignment == "edge":
histalign = "left"
for k in self.axes.keys():
if not self.visibility[k]: continue
dcurr = self.data[k][self.axes[k][0]]
color = colortypes[self.pparm[k][0]]
alpha = self.pparm[k][1]
rwidth = self.pparm[k][2]
self.bins[k],self.edges = np.histogram(dcurr,self.nbins,range=self.xlimits,density=self.normed)
width = (self.edges[1]-self.edges[0])*rwidth
if self.cumulative:
self.bins[k] = np.cumsum(self.bins[k])
if self.normed:
self.bins[k] /= np.sum(self.bins[k])
self.bins[k] /= len(self.axes.keys())
if self.histtype == "bar":
if self.stacked and len(usedkeys) > 0:
bottom = self.getTotals(keys=usedkeys)
ax.bar(self.edges[:-1],self.bins[k], width, color=color,bottom=bottom, align=self.alignment, log=self.logy, orientation=self.orientation, alpha=alpha)
else:
ax.bar(self.edges[:-1],self.bins[k], width, color=color, align=self.alignment, log=self.logy, orientation=self.orientation, alpha=alpha)
usedkeys.append(k)
elif self.histtype == "step" or self.histtype == "stepfilled":
if self.stacked == False:
ax.hist(self.bins[k],bins=self.edges,color=None,range=self.xlimits,histtype=self.histtype, align=histalign, orientation=self.orientation,alpha=self.inspector.alpha.getValue(),normed=self.normed,cumulative=self.cumulative,log=self.logy,stacked=self.stacked)
else:
tostack.append(self.bins[k])
colors.append(color)
if self.histtype == "step" or self.histtype == "stepfilled":
if self.stacked == True:
ax.hist(tostack,bins=self.edges,color=colors,range=self.xlimits,histtype=self.histtype,orientation=self.orientation,align=histalign,alpha=self.inspector.alpha.getValue(),normed=self.normed,cumulative=self.cumulative,log=self.logy,stacked=self.stacked)
self.autoscale(True)
ax.set_ylim(self.ylimits)
canvas.draw()
self.plotimg = canvas.tostring_rgb() # save this and convert to bitmap as needed
# this try except block is because the developers of matplotlib have been changing their API
try: # this would work for matplotlib 0.98
self.scrlim=(ax.get_window_extent().xmin,ax.get_window_extent().ymin,ax.get_window_extent().xmax-ax.get_window_extent().xmin,ax.get_window_extent().ymax-ax.get_window_extent().ymin)
except:
try: # this should work for matplotlib 0.91
self.scrlim=(ax.get_window_extent().xmin(),ax.get_window_extent().ymin(),ax.get_window_extent().xmax()-ax.get_window_extent().xmin(),ax.get_window_extent().ymax()-ax.get_window_extent().ymin())
except:
print 'there is a problem with your matplotlib'
return
self.plotlim=(ax.get_xlim()[0],ax.get_ylim()[0],ax.get_xlim()[1]-ax.get_xlim()[0],ax.get_ylim()[1]-ax.get_ylim()[0])
if not self.glflags.npt_textures_unsupported():
#.........这里部分代码省略.........
示例15: gen_land_bitmap
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import tostring_rgb [as 别名]
def gen_land_bitmap(bmap, resolution_meters):
#Get land polygons and bbox of polygons
polys = []
xmin = np.finfo(np.float64).max
xmax = -np.finfo(np.float64).max
ymin = xmin
ymax = xmax
logging.debug('Rasterizing Basemap, number of land polys: ' + str(len(bmap.landpolygons)))
# If no polys: return a zero map
if (len(bmap.landpolygons) == 0):
raise Exception('Basemap contains no land polys to rasterize')
for polygon in bmap.landpolygons:
coords = polygon.get_coords()
xmin = min(xmin, np.min(coords[:,0]))
xmax = max(xmax, np.max(coords[:,0]))
ymin = min(ymin, np.min(coords[:,1]))
ymax = max(ymax, np.max(coords[:,1]))
polys.append(coords)
xmin = np.floor(xmin/resolution_meters)*resolution_meters
xmax = np.ceil(xmax/resolution_meters)*resolution_meters
ymin = np.floor(ymin/resolution_meters)*resolution_meters
ymax = np.ceil(ymax/resolution_meters)*resolution_meters
# For debugging
logging.debug('Rasterizing Basemap, bounding box: ' + str([xmin, xmax, ymin, ymax]))
# Switch backend to prevent creating an empty figure in notebook
orig_backend = plt.get_backend()
plt.switch_backend('agg')
# Create figure to help rasterize
fig = plt.figure(frameon=False)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
ax.set_xlim(xmin, xmax)
ax.set_ylim(ymin, ymax)
# Set aspect and resolution
# Aspect gives 1 in high plot
aspect = (xmax-xmin)/(ymax-ymin)
resolution_dpi = (ymax-ymin) / resolution_meters
fig.set_dpi(resolution_dpi)
fig.set_size_inches(aspect, 1)
# Add polygons
lc = PolyCollection(polys, facecolor='k', lw=0)
ax.add_collection(lc)
# Create canvas and rasterize
canvas = FigureCanvasAgg(fig)
try:
canvas.draw()
width, height = canvas.get_width_height()
rgb_data = np.fromstring(canvas.tostring_rgb(), dtype='uint8').reshape(height, width, 3)
data = rgb_data[:,:,1]
plt.close(fig) #comment this for debugging purposes and replace with plt.show()
logging.debug('Rasterized size: ' + str([width, height]))
except MemoryError:
gc.collect()
raise Exception('Basemap rasterized size too large: '
+ str(aspect*resolution_dpi) + '*' + str(resolution_dpi)
+ ' cells')
finally:
# Reset backend
plt.switch_backend(orig_backend)
return RasterizedBasemap(xmin, xmax, ymin, ymax, resolution_meters, data)