本文整理汇总了Python中matplotlib.backends.backend_agg.FigureCanvasAgg.print_to_buffer方法的典型用法代码示例。如果您正苦于以下问题:Python FigureCanvasAgg.print_to_buffer方法的具体用法?Python FigureCanvasAgg.print_to_buffer怎么用?Python FigureCanvasAgg.print_to_buffer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.backends.backend_agg.FigureCanvasAgg
的用法示例。
在下文中一共展示了FigureCanvasAgg.print_to_buffer方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: simple
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_to_buffer [as 别名]
def simple():
import datetime
import random
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.dates import DateFormatter
fig = Figure()
ax = fig.add_subplot(111)
x = []
y = []
now = datetime.datetime.now()
delta = datetime.timedelta(days=1)
for i in range(10):
x.append(now)
now += delta
y.append(random.randint(0, 1000))
ax.plot_date(x, y, '-')
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
fig.autofmt_xdate()
canvas = FigureCanvas(fig)
data, shape = canvas.print_to_buffer()
y, x = shape
array = frombuffer(data, dtype=uint8, count=x*y*4)
return array.reshape((x, y, 4))
示例2: test_dpi_setting
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_to_buffer [as 别名]
def test_dpi_setting():
for dpi in range(100, 201, 25):
# note that each figure's resolution is set to a different value based on
# "dpi=DPI" parameter
fig = Figure(figsize=(10,10),
dpi=dpi,
frameon=False)
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.plot([1, 2, 3])
ax.set_title('sample graph')
ax.grid(True)
ax.set_xlabel('time')
ax.set_ylabel('value')
# note that the optional "dpi=dpi" parameter is not passed to
# canvas.print_figure
# without Issue 305 fixed, the resolution would default to 100 DPI regardless
# of figure's actual resolution
# with Issue 305 fixed, the resolution would default to the figure's actual
# resolution
buf, size = canvas.print_to_buffer()
image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
assert image.size == (dpi * 10, dpi * 10)
示例3: serialize
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_to_buffer [as 别名]
def serialize(dataset):
fix_map_attributes(dataset)
fig = Figure(figsize=figsize, dpi=dpi)
ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])
# Set transparent background; found through http://sparkplot.org/browser/sparkplot.py.
if asbool(query.get('TRANSPARENT', 'true')):
fig.figurePatch.set_alpha(0.0)
ax.axesPatch.set_alpha(0.0)
# Plot requested grids (or all if none requested).
layers = [layer for layer in query.get('LAYERS', '').split(',')
if layer] or [var.id for var in walk(dataset, GridType)]
for layer in layers:
names = [dataset] + layer.split('.')
grid = reduce(operator.getitem, names)
if is_valid(grid, dataset):
self._plot_grid(dataset, grid, time, bbox, (w, h), ax, cmap)
# Save to buffer.
ax.axis( [bbox[0], bbox[2], bbox[1], bbox[3]] )
ax.axis('off')
canvas = FigureCanvas(fig)
output = StringIO()
# Optionally convert to paletted png
paletted = asbool(environ.get('pydap.responses.wms.paletted', 'false'))
if paletted:
# Read image
buf, size = canvas.print_to_buffer()
im = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
# Find number of colors
colors = im.getcolors(256)
# Only convert if the number of colors is less than 256
if colors is not None:
ncolors = len(colors)
# Get alpha band
alpha = im.split()[-1]
# Convert to paletted image
im = im.convert("RGB")
im = im.convert("P", palette=Image.ADAPTIVE, colors=ncolors)
# Set all pixel values below ncolors to 1 and the rest to 0
mask = Image.eval(alpha, lambda a: 255 if a <=128 else 0)
# Paste the color of index ncolors and use alpha as a mask
im.paste(ncolors, mask)
# Truncate palette to actual size to save space
im.palette.palette = im.palette.palette[:3*(ncolors+1)]
im.save(output, 'png', optimize=False, transparency=ncolors)
else:
canvas.print_png(output)
else:
canvas.print_png(output)
if hasattr(dataset, 'close'): dataset.close()
return [ output.getvalue() ]
示例4: speed
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_to_buffer [as 别名]
def speed(func):
start = time.time()
s_fig = func()
s_create_time = time.time() - start
s_canvas = FigureCanvas(s_fig)
start = time.time()
f_fig = func(proj='fastticks')
f_create_time = time.time() - start
f_canvas = FigureCanvas(f_fig)
# heat the cache or other first-run issues
f_canvas.print_to_buffer()
s_canvas.print_to_buffer()
ITER=6
start = time.time()
for i in range(ITER):
s_canvas.print_to_buffer()
s_time = time.time() - start
start = time.time()
for i in range(ITER):
f_canvas.print_to_buffer()
f_time = time.time() - start
with Profile(func.__name__):
f_canvas.print_to_buffer()
s_fname = os.path.join('images', '{}.png'.format(func.__name__))
s_fig.savefig(s_fname)
f_fname = os.path.join('images', '{}-fast.png'.format(func.__name__))
f_fig.savefig(f_fname)
identical = open(s_fname, 'rb').read() == open(f_fname, 'rb').read()
print('{:<10s}: {:>5.2f}({:>5.2f}) {:>5.2f}({:>5.2f}) ({:>4.1f}x faster) Identical: {}'.format(func.__name__, s_time, s_create_time, f_time, f_create_time, s_time / f_time, identical))
示例5: vector_field_to_image
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_to_buffer [as 别名]
def vector_field_to_image(vector_field_and_color, rect):
"""
:param vector_field:
:return: ndarray with shape (width, height, 4) and dtype=uint8
"""
vector_field, color = vector_field_and_color
from sympy import lambdify, symbols
from numpy import mgrid, frombuffer, uint8, vectorize
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
x, y = symbols("x y")
u = vectorize(lambdify((x, y),
vector_field[0],
"numpy"))
v = vectorize(lambdify((x, y),
vector_field[1],
"numpy"))
left, top, right, bottom = rect
y, x = mgrid[bottom:top:100j, left:right:100j]
U, V = (u(x, y), v(x, y))
figure = Figure(frameon=False)
figure.patch.set_facecolor('none')
figure.patch.set_alpha(0.0)
figure.set_size_inches(10, 10)
figure.patch.set_visible(False)
figure.subplots_adjust(left=0, right=1, top=1, bottom=0)
axes = figure.add_subplot(111)
axes.streamplot(x, y, U, V, color=color)
axes.axis('off')
axes.patch.set_visible(False)
canvas = FigureCanvas(figure)
data, shape = canvas.print_to_buffer()
y, x = shape
array = frombuffer(data, dtype=uint8, count=x*y*4)
return array.reshape((x, y, 4))
示例6: marker_image
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_to_buffer [as 别名]
def marker_image(path, size, trans,
edgecolor='k', facecolor = 'b',
edgewidth= 1.0):
fig = Figure(figsize=((size*2+1)/72., (size*2+1)/72.), dpi = 72)
#fig.set_edgecolor([1,1,1,0])
#fig.set_facecolor([1,1,1,0])
fig.set_edgecolor([0,0,0,0])
fig.set_facecolor([0,0,0,0])
fig.patch.set_alpha(0.0)
fig.clf()
fig.frameon = False
ax = fig.add_subplot(111)
ax.set_position((0,0,1,1))
ed=ax.transAxes.transform([(0,0), (1,1)])
path = trans.transform_path(path)
patch = patches.PathPatch(path, facecolor=facecolor, edgecolor=edgecolor,
lw=edgewidth)
ax.patch.set_facecolor([0,0,0,0])
ax.patch.set_edgecolor([0,0,0,0])
ax.patch.set_alpha(0.0)
ax.add_patch(patch)
ax.set_xlim(-1,1)
ax.set_ylim(-1,1)
ax.tick_params(length=0)
ax.set_axis_off()
canvas = FigureCanvasAgg(fig)
buff, size = canvas.print_to_buffer()
im = np.fromstring(buff, np.uint8).reshape(size[1], size[0], -1)
#idx = np.where(im[:,:,-1] == 0)
#im[:,:,0][idx] = 0
#im[:,:,1][idx] = 0
#im[:,:,2][idx] = 0
return im
示例7: atoms_quantities_to_image
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_to_buffer [as 别名]
def atoms_quantities_to_image(name_and_quantity_list, matter_name):
"""
:param name_and_quantity_list: list of pairs (name, quantity)
where name stands for Atom name and quantity stands for number of
atoms in specific matter
:return: ndarray with shape (width, height, 4) and dtype=uint8
"""
from matplotlib.figure import Figure
from numpy import arange, frombuffer, uint8
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
if name_and_quantity_list:
names, quantities = zip(*name_and_quantity_list)
pos = arange(len(names))
else:
names = []
quantities = []
pos = arange(len(names))
figure = Figure()
figure.patch.set_facecolor('none')
figure.patch.set_alpha(0.0)
figure.set_size_inches(5, 5)
axes = figure.add_subplot(111)
axes.barh(pos, quantities, align='center', alpha=0.4)
axes.yaxis.set_ticks(pos)
axes.yaxis.set_ticklabels(names)
axes.set_xlabel('Quantity')
axes.set_title(matter_name)
axes.patch.set_visible(False)
canvas = FigureCanvas(figure)
data, shape = canvas.print_to_buffer()
y, x = shape
array = frombuffer(data, dtype=uint8, count=x*y*4)
return array.reshape((x, y, 4))
示例8: __init__
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_to_buffer [as 别名]
class Plot:
def __init__(self, x_size=640, y_size=480):
self.data_x = list(range(101))
self.data_y1 = [random()]
self.data_y2 = [self.data_y1[0]]
for _ in range(100):
r = random()
self.data_y1.append((self.data_y1[-1] + r) / 2.0)
self.data_y2.append(self.data_y2[-1] + r)
self.fig = Figure(figsize=(x_size / 100.0, y_size / 100.0), dpi=100.0)
# The first graph
self.ax1 = self.fig.add_subplot(1, 1, 1)
[self.line1_data] = self.ax1.step(
self.data_x,
self.data_y1,
'g-',
label="Nearly random data",
)
# X axis decoration
self.ax1.set_xlim([0, 100])
self.ax1.set_xlabel("A series of 100 values")
# Y axis decoration
self.ax1.set_ylabel("How much?")
self.ax1.set_autoscaley_on(False)
self.ax1.set_ylim([0.0, 1.0])
self.ax1.set_yticks((0.0, 0.33, 0.66, 1.00))
self.y_labels = self.ax1.set_yticklabels(
('None', 'Some', 'Much', 'Lots')
)
for label in self.y_labels:
label.set_rotation(45)
# A second graph with a different axis on the same plot
self.ax2 = self.ax1.twinx()
self.ax2.set_autoscaley_on(True)
[self.line2_data] = self.ax2.plot(
self.data_x,
self.data_y2,
'r-',
label="Summed random data",
)
# Title, legend and grid
self.ax1.set_title("A matplotlib figure")
self.ax1.legend(loc='lower right')
self.ax1.grid()
# FIXME: This doesn't work yet; see comments in draw().
# self.fig.patch.set_alpha(0.5)
# self.ax1.patch.set_alpha(0.5)
self.canvas = FigureCanvasAgg(self.fig)
def draw(self):
r = random()
self.data_y1.append((self.data_y1[-1] + r) / 2.0)
self.data_y1.pop(0)
self.data_y2.append(self.data_y2[-1] + r)
self.data_y2.pop(0)
# If your y axis limits are going to change, you need:
# self.line_data.set_ydata(self.data_y)
# or set limits explicitly, as shown in __init__().
# set_data() doesn't realign them, but is cheaper.
self.line1_data.set_data(self.data_x, self.data_y1)
self.line2_data.set_ydata(self.data_y2)
graph_bytes, _res = self.canvas.print_to_buffer()
return graph_bytes
示例9: figure
# 需要导入模块: from matplotlib.backends.backend_agg import FigureCanvasAgg [as 别名]
# 或者: from matplotlib.backends.backend_agg.FigureCanvasAgg import print_to_buffer [as 别名]
# A canvas must be manually attached to the figure (pyplot would automatically
# do it). This is done by instantiating the canvas with the figure as
# argument.
canvas = FigureCanvasAgg(fig)
# Do some plotting.
ax = fig.add_subplot(111)
ax.plot([1, 2, 3])
# Option 1: Save the figure to a file; can also be a file-like object (BytesIO,
# etc.).
fig.savefig("test.png")
# Option 2: Save the figure to a string.
canvas.draw()
s, (width, height) = canvas.print_to_buffer()
# Option 2a: Convert to a NumPy array.
X = np.fromstring(s, np.uint8).reshape((height, width, 4))
# Option 2b: Pass off to PIL.
from PIL import Image
im = Image.frombytes("RGBA", (width, height), s)
# Uncomment this line to display the image using ImageMagick's `display` tool.
# im.show()
#############################################################################
#
# ------------
#