def histogram(message):
"""
Generate a histogram from a list of numbers separated by new lines, semi-colons,
commas, or spaces. Currently, the bin count is locked to 10.
Example::
/hist 20 39 19 17 28 39 29 20 11 29 32 44
/roll 500d10 | hist
"""
data = parse_numeric_list(message.content)
def execute():
with lock:
plt.figure(1, figsize=(5, 5))
ax = plt.axes([0.1, 0.1, 0.4, 0.4])
plt.hist(data, bins=10)
prop = fm.FontProperties(fname=font_path, size=11)
for text in ax.texts:
text.set_fontproperties(prop)
buf = io.BytesIO()
plt.savefig(buf, bbox_inches='tight', transparent=False, pad_inches=0.1)
plt.clf()
return buf
buf = await asyncio.get_event_loop().run_in_executor(None, execute)
return Response("", attachments=[MemoryAttachment(buf, "graph.png", "image/png")])
python类FontProperties()的实例源码
def fontprop(ax, name, size=12):
assert name in available_fonts, "Font must be one of {0}.".\
format(available_fonts)
import matplotlib.font_manager as fm
fname = op.join(datadir, name)
prop = fm.FontProperties(fname=fname, size=size)
logging.debug("Set font to `{0}` (`{1}`).".format(name, prop.get_file()))
for text in ax.texts:
text.set_fontproperties(prop)
return prop
def _set_legend(self):
'''
Tweak font to be small and place *legend*
in the upper right corner of the figure
'''
font = font_manager.FontProperties(size='small')
self._axes.legend(loc='upper right', prop=font)
def wrap(self, aW, aH):
if HAS_MATPLOTLIB:
try:
width, height, descent, glyphs, \
rects, used_characters = self.parser.parse(
enclose(self.s), 72, prop=FontProperties(size=self.fontsize))
return width, height
except:
pass
# FIXME: report error
return 10, 10
def descent(self):
"""Return the descent of this flowable,
useful to align it when used inline."""
if HAS_MATPLOTLIB:
width, height, descent, glyphs, rects, used_characters = \
self.parser.parse(enclose(self.s), 72, prop=FontProperties(size=self.fontsize))
return descent
return 0
def init(self):
prop = font_manager.FontProperties(fname = self.font_path)
matplotlib.rcParams['font.family'] = prop.get_name()
try:
command = "SELECT product_color, product_size, user_level_name, user_province, reference_time, " \
"creation_time,is_mobile, user_client_show, days, user_level_name FROM {0}". \
format('item_%s' % self.product_id)
result = self.sql.query(command, commit = False, cursor_type = 'dict')
self.data_frame = DataFrame(result)
except Exception, e:
logging.exception('analysis init exception msg:%s' % e)
raise CusException('analysis_init', 'analysis_init error:%s' % e)
def plot_init(self, name, fig_specs=None, save=False):
#add a figure with a single subplot
if save==True:
import matplotlib
matplotlib.use('Agg') # non-interactive backend
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
fontP = FontProperties()
fontP.set_size('small')
self.colors = ['-r','-b','-m','-g']
if self.fig==None:
self.fig = plt.figure(figsize=(8,4))
if fig_specs != None:
# fig_spec is a dictionary of fig adjust specs
self.fig.subplots_adjust(**fig_sepcs)
else:
self.fig.subplots_adjust(left = 0.15, bottom = 0.07,
right = 0.94, top = 0.94,
hspace = 0.14, wspace=0.20)
if type(name) != str:
raise TypeError('name should be a string')
layout = 'grid'
n = len(self.fig.axes)
if layout in ('h', 'horizontal'):
n_rows, n_cols = (1, n+1)
elif layout in ('v', 'vertical'):
n_rows, n_cols = (n+1, 1)
elif layout in ('g', 'grid'):
vector_length=n+1
n_cols = int(np.ceil(np.sqrt(vector_length)))
n_rows = int(np.ceil(vector_length/n_cols))
else:
raise ValueError('Bad layout Value')
for i in range(n):
self.fig.axes[i].change_geometry(n_rows, n_cols, i+1)
self.figsaxe[name] = self.fig.add_subplot(n_rows, n_cols, n+1)
def set_font(self, font_dict=None):
"""
Set the font and font properties.
Parameters
----------
font_dict : dict
A dict of keyword parameters to be passed to
:class:`matplotlib.font_manager.FontProperties`.
Possible keys include:
* family - The font family. Can be serif, sans-serif, cursive,
'fantasy', or 'monospace'.
* style - The font style. Either normal, italic or oblique.
* color - A valid color string like 'r', 'g', 'red', 'cobalt',
and 'orange'.
* variant - Either normal or small-caps.
* size - Either a relative value of xx-small, x-small, small,
medium, large, x-large, xx-large or an absolute font size, e.g. 12
* stretch - A numeric value in the range 0-1000 or one of
ultra-condensed, extra-condensed, condensed, semi-condensed,
normal, semi-expanded, expanded, extra-expanded or ultra-expanded
* weight - A numeric value in the range 0-1000 or one of ultralight,
light, normal, regular, book, medium, roman, semibold, demibold,
demi, bold, heavy, extra bold, or black
See the matplotlib font manager API documentation for more details.
http://matplotlib.org/api/font_manager_api.html
Notes
-----
Mathtext axis labels will only obey the `size` and `color` keyword.
Examples
--------
This sets the font to be 24-pt, blue, sans-serif, italic, and
bold-face.
>>> prof = ProfilePlot(ds.all_data(), 'density', 'temperature')
>>> slc.set_font({'family':'sans-serif', 'style':'italic',
... 'weight':'bold', 'size':24, 'color':'blue'})
"""
from matplotlib.font_manager import FontProperties
if font_dict is None:
font_dict = {}
if 'color' in font_dict:
self._font_color = font_dict.pop('color')
# Set default values if the user does not explicitly set them.
# this prevents reverting to the matplotlib defaults.
font_dict.setdefault('family', 'stixgeneral')
font_dict.setdefault('size', 18)
self._font_properties = \
FontProperties(**font_dict)
return self
def set_font(self, font_dict=None):
"""
Set the font and font properties.
Parameters
----------
font_dict : dict
A dict of keyword parameters to be passed to
:class:`matplotlib.font_manager.FontProperties`.
Possible keys include:
* family - The font family. Can be serif, sans-serif, cursive,
'fantasy' or 'monospace'.
* style - The font style. Either normal, italic or oblique.
* color - A valid color string like 'r', 'g', 'red', 'cobalt',
and 'orange'.
* variant - Either normal or small-caps.
* size - Either a relative value of xx-small, x-small, small,
medium, large, x-large, xx-large or an absolute font size, e.g. 12
* stretch - A numeric value in the range 0-1000 or one of
ultra-condensed, extra-condensed, condensed, semi-condensed,
normal, semi-expanded, expanded, extra-expanded or ultra-expanded
* weight - A numeric value in the range 0-1000 or one of ultralight,
light, normal, regular, book, medium, roman, semibold, demibold,
demi, bold, heavy, extra bold, or black
See the matplotlib font manager API documentation for more details.
http://matplotlib.org/api/font_manager_api.html
Notes
-----
Mathtext axis labels will only obey the `size` and `color` keyword.
Examples
--------
This sets the font to be 24-pt, blue, sans-serif, italic, and
bold-face.
>>> slc = SlicePlot(ds, 'x', 'Density')
>>> slc.set_font({'family':'sans-serif', 'style':'italic',
... 'weight':'bold', 'size':24, 'color':'blue'})
"""
from matplotlib.font_manager import FontProperties
if font_dict is None:
font_dict = {}
if 'color' in font_dict:
self._font_color = font_dict.pop('color')
# Set default values if the user does not explicitly set them.
# this prevents reverting to the matplotlib defaults.
font_dict.setdefault('family', 'stixgeneral')
font_dict.setdefault('size', 18)
self._font_properties = \
FontProperties(**font_dict)
return self
def plot_batches(fulldata, cols=None, out_file=None, site_labels='left'):
fulldata = fulldata.sort_values(by=['database', 'site']).copy()
sites = fulldata.site.values.ravel().tolist()
if cols is None:
numdata = fulldata.select_dtypes([np.number])
else:
numdata = fulldata[cols]
numdata = numdata[cols]
colmin = numdata.min()
numdata = (numdata - colmin)
colmax = numdata.max()
numdata = numdata / colmax
fig, ax = plt.subplots(figsize=(20, 10))
ax.imshow(numdata.values, cmap=plt.cm.viridis, interpolation='nearest', aspect='auto')
locations = []
spines = []
fulldata['index'] = range(len(fulldata))
for site in list(set(sites)):
indices = fulldata.loc[fulldata.site == site, 'index'].values.ravel().tolist()
locations.append(int(np.average(indices)))
spines.append(indices[0])
if site_labels == 'right':
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
plt.xticks(range(numdata.shape[1]), numdata.columns.ravel().tolist(), rotation='vertical')
plt.yticks(locations, list(set(sites)))
for line in spines[1:]:
plt.axhline(y=line, color='w', linestyle='-')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.grid(False)
ticks_font = FontProperties(
family='FreeSans', style='normal', size=14,
weight='normal', stretch='normal')
for label in ax.get_yticklabels():
label.set_fontproperties(ticks_font)
ticks_font = FontProperties(
family='FreeSans', style='normal', size=12,
weight='normal', stretch='normal')
for label in ax.get_xticklabels():
label.set_fontproperties(ticks_font)
if out_file is not None:
fig.savefig(out_file, bbox_inches='tight', pad_inches=0, dpi=300)
return fig
def simple_plot(figure,X,Y,colors,xlabel="",ylabel="",linked=True,n_points=400,marker_size=10,linewidth=3,alpha=1.0,label=None):
"""
"""
if np.array(colors).ndim == 1:
colors = np.array([colors for i in xrange(len(X))])
#font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light')
font = fm.FontProperties(family = 'Trebuchet', weight ='light')
figure.patch.set_facecolor('white')
axes = figure.add_subplot(111)
if linked:
X_smooth = np.linspace(X.min(),X.max(),n_points)
interpolator = interp1d(X,Y)
Y_smooth = np.array([interpolator(x) for x in X_smooth])
color_interpolator = [interp1d(X,colors[:,k]) for k in [0,1,2]]
colors_smooth = np.transpose([[color_interpolator[k](x) for x in X_smooth] for k in [0,1,2]])
for i in xrange(100):
# color = tuple(color1*(1.0-i/100.0) + color2*(i/100.0))
color = colors_smooth[(i*n_points/100):((i+1)*n_points)/100+1].mean(axis=0)
if i == 0:
axes.plot(X_smooth[(i*n_points/100):((i+1)*n_points)/100+1],Y_smooth[(i*n_points/100):((i+1)*n_points)/100+1],linewidth=linewidth,color=color,alpha=alpha,label=label if marker_size==0 else None)
else:
axes.plot(X_smooth[(i*n_points/100):((i+1)*n_points)/100+1],Y_smooth[(i*n_points/100):((i+1)*n_points)/100+1],linewidth=linewidth,color=color,alpha=alpha)
# axes.plot(X,Y,linewidth=linewidth,color=color,alpha=alpha,label=label)
# ratios = (Y-Y.min())/(Y.max()-Y.min())
axes.scatter(X,Y,c=colors,label=label if marker_size>0 else None,s=marker_size,alpha=alpha,linewidth=linewidth)
# colors =
# for i in xrange(100):
# color = tuple(color1*(1.0-ratios[i]) + color2*ratios[i])
# axes.plot(X_smooth[(i*n_points/100):((i+1)*n_points)/100+1],Y_smooth[(i*n_points/100):((i+1)*n_points)/100+1],linewidth=linewidth,color=color,alpha=1.0)
axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic')
# axes.set_xlim(X.min(),X.max())
axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12)
axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic')
# axes.set_ylim(Y.min(),Y.max())
axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
def density_contour_plot(figure,X,Y,color,XY_range=None,xlabel="",ylabel="",n_points=100,n_contours=10,smooth_factor=1.0,linewidth=1,marker_size=40.,alpha=1.0,label=""):
font = fm.FontProperties(family = 'Trebuchet', weight ='light')
figure.patch.set_facecolor('white')
axes = figure.add_subplot(111)
if XY_range is None:
XY_range = [[X.min(),X.max()],[Y.min(),Y.max()]]
range_x = np.linspace(XY_range[0][0],XY_range[0][1],n_points)
range_y = np.linspace(XY_range[1][0],XY_range[1][1],n_points)
xx, yy = np.meshgrid(range_x,range_y)
range_x_cr = (range_x - range_x.mean())/range_x.std()
range_y_cr = (range_y - range_y.mean())/range_y.std()
xx_cr, yy_cr = np.meshgrid(range_x_cr,range_y_cr)
def density_function(positions,radius=1,k=0.1):
def density_func(x,y):
points = np.array(positions.values())
if len((x+y).shape) == 1:
distances = np.power(np.power(x[np.newaxis] - points[:,0,np.newaxis],2) + np.power(y[np.newaxis] - points[:,1,np.newaxis],2),0.5)
elif len((x+y).shape) == 2:
distances = np.power(np.power(x[np.newaxis] - points[:,0,np.newaxis,np.newaxis],2) + np.power(y[np.newaxis] - points[:,1,np.newaxis,np.newaxis],2),0.5)
density_potential = 1./2. * (1. - np.tanh(k*(distances - radius)))
density = density_potential.sum(axis=0)
return density
return density_func
positions = dict(zip(range(len(X)),np.transpose([X,Y])))
positions_cr = dict(zip(range(len(X)),np.transpose([(X-range_x.mean())/range_x.std(),(Y-range_y.mean())/range_y.std()])))
# radius = np.sqrt((X.std() * Y.std()))
radius = 10.0/n_points
density_k = 100.*np.exp(-smooth_factor/2.)
data_density = density_function(positions_cr,radius,density_k)(xx_cr,yy_cr)
levels = np.linspace(0,data_density.max(),n_contours)
colors = np.array([(lev*color + (n_contours-1-lev)*np.ones(3))/(n_contours-1) for lev in xrange(n_contours)])
axes.scatter(X,Y,s=marker_size,c=color,linewidth=0,alpha=alpha/2.,label=label)
axes.contour(xx,yy,data_density,linewidths=linewidth,levels=levels,colors=colors,alpha=(alpha+1)/2.)
axes.set_xlim(*tuple(XY_range[0]))
axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic')
axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12)
axes.set_ylim(*tuple(XY_range[1]))
axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic')
axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
def heatmap(name, data, title, text):
fig, ax = plt.subplots()
ticks_font = font_manager.FontProperties(family='Decima Mono')
plt.style.use([os.path.join(sys.path[0], 'ethplot.mplstyle')])
LEFT = 0.125
fig.suptitle(title,
horizontalalignment='left',
weight='bold', fontsize=20,
x=LEFT, y=1)
t = fig.text(LEFT, 0.92, text,
horizontalalignment='left',
weight='medium', fontsize=16, color='#555555')
labels1 = ['PR','HD','SSSP','SCC']
labels2 = ['PR','HD','SSSP','SCC']
ax.set_xticklabels(labels1)
ax.set_yticklabels(labels2)
ax.set_yticks(np.arange(data.shape[0]) + 0.5)
ax.set_xticks(np.arange(data.shape[1]) + 0.5)
ax.tick_params(pad=11)
plt.setp(ax.get_xticklabels(), fontproperties=ticks_font)
plt.setp(ax.get_yticklabels(), fontproperties=ticks_font)
norm = MidpointNormalize(midpoint=1.0)
c = plt.pcolor(data, cmap = colors, vmin=0.5, vmax=2.5, norm=norm)
values = data.as_matrix()
for x in range(data.shape[0]):
for y in range(data.shape[1]):
#color = 'white' if values[y][x] > 2.3 else 'black'
color = 'black'
plt.text(x + 0.5, y + 0.5, '%.2f' % values[y][x],
horizontalalignment='center',
verticalalignment='center',
color=color,
fontproperties=ticks_font)
colorbar = plt.colorbar(c)
plt.setp(colorbar.ax.get_yticklabels(), fontproperties=ticks_font)
plt.savefig(name + ".png", format='png')
#ppad_inched=0.08 here because otherwise it cuts off the numbers...
#plt.savefig(name + ".pdf", format='pdf', pad_inches=0.08)
def heatmap(name, data, title, text):
fig, ax = plt.subplots()
ticks_font = font_manager.FontProperties(family='Decima Mono')
plt.style.use([os.path.join(sys.path[0], 'ethplot.mplstyle')])
#savefig.pad_inches: 0.08
LEFT = 0.125
fig.suptitle(title,
horizontalalignment='left',
weight='bold', fontsize=20,
x=LEFT, y=1)
t = fig.text(LEFT, 0.92, text,
horizontalalignment='left',
weight='medium', fontsize=16, color='#555555')
labels1 = ['PR','HD','SSSP','SCC']
labels2 = ['PR','HD','SSSP','SCC']
ax.set_xticklabels(labels1)
ax.set_yticklabels(labels2)
ax.set_yticks(np.arange(data.shape[0]) + 0.5)
ax.set_xticks(np.arange(data.shape[1]) + 0.5)
ax.tick_params(pad=11)
plt.setp(ax.get_xticklabels(), fontproperties=ticks_font)
plt.setp(ax.get_yticklabels(), fontproperties=ticks_font)
c = plt.pcolor(data, cmap = cm.Greys, vmin=1.0, vmax=2.5)
values = data.as_matrix()
for x in range(data.shape[0]):
for y in range(data.shape[1]):
color = 'white' if values[y][x] > 2.3 else 'black'
plt.text(x + 0.5, y + 0.5, '%.2f' % values[y][x],
horizontalalignment='center',
verticalalignment='center',
color=color,
fontproperties=ticks_font)
colorbar = plt.colorbar(c)
plt.setp(colorbar.ax.get_yticklabels(), fontproperties=ticks_font)
plt.savefig(name + ".png", format='png')
#ppad_inched=0.08 here because otherwise it cuts off the numbers...
#plt.savefig(name + ".pdf", format='pdf', pad_inches=0.08)
document_clustering.py 文件源码
项目:text-analytics-with-python
作者: dipanjanS
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def plot_clusters(num_clusters, feature_matrix,
cluster_data, movie_data,
plot_size=(16,8)):
# generate random color for clusters
def generate_random_color():
color = '#%06x' % random.randint(0, 0xFFFFFF)
return color
# define markers for clusters
markers = ['o', 'v', '^', '<', '>', '8', 's', 'p', '*', 'h', 'H', 'D', 'd']
# build cosine distance matrix
cosine_distance = 1 - cosine_similarity(feature_matrix)
# dimensionality reduction using MDS
mds = MDS(n_components=2, dissimilarity="precomputed",
random_state=1)
# get coordinates of clusters in new low-dimensional space
plot_positions = mds.fit_transform(cosine_distance)
x_pos, y_pos = plot_positions[:, 0], plot_positions[:, 1]
# build cluster plotting data
cluster_color_map = {}
cluster_name_map = {}
for cluster_num, cluster_details in cluster_data.items():
# assign cluster features to unique label
cluster_color_map[cluster_num] = generate_random_color()
cluster_name_map[cluster_num] = ', '.join(cluster_details['key_features'][:5]).strip()
# map each unique cluster label with its coordinates and movies
cluster_plot_frame = pd.DataFrame({'x': x_pos,
'y': y_pos,
'label': movie_data['Cluster'].values.tolist(),
'title': movie_data['Title'].values.tolist()
})
grouped_plot_frame = cluster_plot_frame.groupby('label')
# set plot figure size and axes
fig, ax = plt.subplots(figsize=plot_size)
ax.margins(0.05)
# plot each cluster using co-ordinates and movie titles
for cluster_num, cluster_frame in grouped_plot_frame:
marker = markers[cluster_num] if cluster_num < len(markers) \
else np.random.choice(markers, size=1)[0]
ax.plot(cluster_frame['x'], cluster_frame['y'],
marker=marker, linestyle='', ms=12,
label=cluster_name_map[cluster_num],
color=cluster_color_map[cluster_num], mec='none')
ax.set_aspect('auto')
ax.tick_params(axis= 'x', which='both', bottom='off', top='off',
labelbottom='off')
ax.tick_params(axis= 'y', which='both', left='off', top='off',
labelleft='off')
fontP = FontProperties()
fontP.set_size('small')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.01), fancybox=True,
shadow=True, ncol=5, numpoints=1, prop=fontP)
#add labels as the film titles
for index in range(len(cluster_plot_frame)):
ax.text(cluster_plot_frame.ix[index]['x'],
cluster_plot_frame.ix[index]['y'],
cluster_plot_frame.ix[index]['title'], size=8)
# show the plot
plt.show()
visualization.py 文件源码
项目:caption-guided-saliency
作者: VisionLearningGroup
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def get_superimposed_frame(video_id, frame_filename, saliency_frame, sentence):
from matplotlib.font_manager import FontProperties
font0 = FontProperties()
font0.set_family("sans-serif")
def generate_saliency(spatial_attention, image_size, norm = False):
minimum = np.amin(spatial_attention)
maximum = np.amax(spatial_attention)
spatial_attention = np.pad(spatial_attention, pad_width = ((1, 1), (1, 1)),
mode = 'constant', constant_values=np.amin(spatial_attention))
saliency_image = Image.fromarray(np.uint8((spatial_attention) * float(255)), 'L').resize(image_size, Image.BICUBIC)
saliency_image = saliency_image.resize((int(image_size[0] * 1.2), int(image_size[1] * 1.2)), Image.BICUBIC)
saliency_image = saliency_image.crop((int(image_size[0] * 0.1 ), int(image_size[1] * 0.1 ), int(image_size[0] * 1.1), int(image_size[0] * 1.1) ))
return saliency_image
original_image = Image.open(frame_filename).resize((SCALE, SCALE),
Image.ANTIALIAS)
n_words = saliency_frame.shape[0]
w = np.floor(np.sqrt(n_words))
h = np.ceil(np.float32(n_words) / w )
figw, figh = int(h * 3), int(w * 3)
f = plt.figure(figsize=(figw, figh), facecolor = "black", dpi = 150)
for word_idx in range(saliency_frame.shape[0]):
plt.subplot(w, h, word_idx+1)
plt.imshow(original_image)
saliency = generate_saliency(saliency_frame[word_idx].reshape(8, 8),
(SCALE, SCALE), norm = False)
saliency = np.asarray(saliency) / 255.
plt.imshow(saliency, vmin=0.0, vmax=1.0, alpha = 0.5, cmap="jet")
fontsize = 12 + (h - 2) * 2
plt.text(6, 18, sentence[word_idx], fontproperties = font0,
color = "black", backgroundcolor='white', fontsize=fontsize)
plt.axis('off')
plt.tick_params(axis='both', left='off', top='off', right='off',
bottom='off', labelleft='off', labeltop='off',
labelright='off', labelbottom='off')
bezel_thickness = 0.02
plt.tight_layout(pad = bezel_thickness, w_pad=bezel_thickness, h_pad=bezel_thickness)
plt.subplots_adjust(hspace = bezel_thickness , # ,
wspace = bezel_thickness )
plt.savefig(path.join(path_to_save_figures, video_id, frame_filename.split("/")[-1] + ".png"),
bbox_inches='tight',
facecolor=f.get_facecolor(),
dpi=90,
edgecolor='none')
plt.close()
def pie(message):
"""
Generate a pie graph. To specify the parts of the pie, make a
list separated by new lines, semi-colons or commas where each
list entry has a percentage in it (if there is more than one, the
first percentage is used).
To specify a graph title, don't provide a percentage for one of the
list items.
Example::
/pie Materials, 40% Glass, 22%
The percentages do not need to add up to 100%. If they do not, then
the percentage values will be normalized so that they do add up to 100%.
"""
title, labels, data = extract_data(message.content, pattern=PERCENTAGE_PATTERN, normalize=True)
def execute():
with lock:
plt.figure(1, figsize=(5, 5))
ax = plt.axes([0.1, 0.1, 0.4, 0.4])
plt.pie(data, labels=labels, autopct='%1.0f%%', startangle=90)
if title:
plt.title(title)
prop = fm.FontProperties(fname=font_path, size=11)
for text in ax.texts:
text.set_fontproperties(prop)
buf = io.BytesIO()
plt.savefig(buf, bbox_inches='tight', transparent=False, pad_inches=0.1)
plt.clf()
return buf
buf = await asyncio.get_event_loop().run_in_executor(None, execute)
return Response("", attachments=[MemoryAttachment(buf, "graph.png", "image/png")])
def bar(message):
"""
Generate a bar graph. To specify the individual bar labels and values, make a
list separated by new lines, semi-colons or commas where each
list entry has a number in it (if there is more than one, the
first number is used).
To specify a graph title, don't provide a number for one of the
list items.
Example::
/bar Groups, Man O 100, rationale. 20
"""
title, labels, data = extract_data(message.content, pattern=NUMBER_PATTERN)
def execute():
width = 0.8
ind = np.arange(len(data)) - width
with lock:
plt.figure(1, figsize=(5, 5))
ax = plt.axes([0.1, 0.1, 0.4, 0.4])
plt.bar(ind, data, width, align='center')
plt.xticks(rotation=70)
ax.set_xticks(ind)
ax.set_xticklabels(labels)
if title:
plt.title(title)
prop = fm.FontProperties(fname=font_path, size=11)
for text in ax.texts:
text.set_fontproperties(prop)
buf = io.BytesIO()
plt.savefig(buf, bbox_inches='tight', transparent=False, pad_inches=0.1)
plt.clf()
return buf
buf = await asyncio.get_event_loop().run_in_executor(None, execute)
return Response("", attachments=[MemoryAttachment(buf, "graph.png", "image/png")])
def view(self,bondselect=None,termselect=None,pidon=True,bonddr='+',show=True,suspend=False,close=True):
'''
View the index packs of the terms on the bonds.
Parameters
----------
bondselect : callable, optional
The select function of the bonds.
termselect : callable, optional
The select function of the terms.
pidon : logical, optional
True for showing the pids of the points of the bonds.
bonddr : '+'/'-', optional
The direction of the bonds.
show : logical, optional
True for showing the view and False for not.
suspend : logical, optional
True for suspending the view and False for not.
close : logical, optional
True for closing the view and False for not.
'''
plt.axis('off')
plt.axis('equal')
xmax,xmin,ymax,ymin=0,0,0,0
points,font=set(),FontProperties(style='italic',weight='bold',size='large')
for bond in self.bonds:
assert len(bond.rcoord)==2
for i,point in enumerate([bond.spoint,bond.epoint]):
pid=point.pid
xmax,xmin=max(xmax,point.rcoord[0]),min(xmin,point.rcoord[0])
ymax,ymin=max(ymax,point.rcoord[1]),min(ymin,point.rcoord[1])
if pid not in points:
x,y=point.rcoord if i==0 else point.rcoord-bond.icoord
plt.scatter(x,y,zorder=2,alpha=0.5)
if pidon: plt.text(x,y,'%s%s'%('' if pid.scope is None else '%s*'%pid.scope,pid.site),color='blue',horizontalalignment='center',fontproperties=font)
points.add(point.pid)
if bondselect is None or bondselect(bond):
assert bonddr in ('+','-')
(x,y),(dx,dy)=(bond.spoint.rcoord,bond.rcoord) if bonddr=='+' else (bond.epoint.rcoord,bond.reversed.rcoord)
if nl.norm(bond.rcoord)>RZERO: plt.arrow(x,y,dx,dy,ls='--' if nl.norm(bond.icoord)>RZERO else '-',lw=2,color='red',length_includes_head=True,alpha=0.5)
packs=[term.strrep(bond,self.config) for term in it.chain(self.terms['const'],self.terms['alter']) if termselect is None or termselect(term)]
if len(packs)>0:
plt.text(x+dx/2,y+dy/2,'\n'.join(sorted(packs,key=len)),color='green',horizontalalignment='center',verticalalignment='center',fontproperties=font)
plt.xlim([xmin-(xmax-xmin)*0.30,xmax+(xmax-xmin)*0.30])
plt.ylim([ymin-(ymax-ymin)*0.30,ymax+(ymax-ymin)*0.30])
if show and suspend: plt.show()
if show and not suspend: plt.pause(1)
if close: plt.close()
def drawOn(self, canv, x, y, _sW=0):
if _sW and hasattr(self,'hAlign'):
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT, TA_JUSTIFY
a = self.hAlign
if a in ('CENTER','CENTRE', TA_CENTER):
x = x + 0.5*_sW
elif a in ('RIGHT',TA_RIGHT):
x = x + _sW
elif a not in ('LEFT',TA_LEFT):
raise ValueError, "Bad hAlign value "+str(a)
height = 0
if HAS_MATPLOTLIB:
global fonts
canv.saveState()
canv.translate(x, y)
try:
width, height, descent, glyphs, \
rects, used_characters = self.parser.parse(
enclose(self.s), 72, prop=FontProperties(size=self.fontsize))
for ox, oy, fontname, fontsize, num, symbol_name in glyphs:
if not fontname in fonts:
fonts[fontname] = fontname
pdfmetrics.registerFont(TTFont(fontname, fontname))
canv.setFont(fontname, fontsize)
col_conv=ColorConverter()
rgb_color=col_conv.to_rgb(self.color)
canv.setFillColorRGB(rgb_color[0],rgb_color[1],rgb_color[2])
canv.drawString(ox, oy, unichr(num))
canv.setLineWidth(0)
canv.setDash([])
for ox, oy, width, height in rects:
canv.rect(ox, oy+2*height, width, height, fill=1)
except:
# FIXME: report error
col_conv=ColorConverter()
rgb_color=col_conv.to_rgb(self.color)
canv.setFillColorRGB(rgb_color[0],rgb_color[1],rgb_color[2])
canv.drawString(0,0,self.s)
canv.restoreState()
else:
canv.saveState()
canv.drawString(x, y, self.s)
canv.restoreState()
if self.label:
log.info('Drawing equation-%s'%self.label)
canv.bookmarkHorizontal('equation-%s'%self.label,0,height)