我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.font_manager.FontProperties()。
def display_results_figure(results, METRIC): import pylab as pb color = iter(pb.cm.rainbow(np.linspace(0, 1, len(results)))) plots = [] for method in results.keys(): x = [] y = [] for train_perc in sorted(results[method].keys()): x.append(train_perc) y.append(results[method][train_perc][0]) c = next(color) (pi, ) = pb.plot(x, y, color=c) plots.append(pi) from matplotlib.font_manager import FontProperties fontP = FontProperties() fontP.set_size('small') pb.legend(plots, map(method_name_mapper, results.keys()), prop=fontP, bbox_to_anchor=(0.6, .65)) pb.xlabel('#Tweets from target rumour for training') pb.ylabel('Accuracy') pb.title(METRIC.__name__) pb.savefig('incrementing_training_size.png')
def pieGraphics(Labels,ValueList,graphicTitle='??'): colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral', "blue","green","cyan","magenta"] maxdata = max(ValueList) explode = [] for v in ValueList: if v == maxdata: explode.append(0.1) else: explode.append(0) print(explode) patches,l_text,p_text = plt.pie(ValueList, labels=Labels, colors=colors,autopct='%1.1f%%',explode=explode ,shadow=True, startangle=90) for font in l_text: font.set_fontproperties(FontProperties(fname=PATH_SUFFIX+'SIMLI.TTF')) plt.title(graphicTitle,fontproperties=font_set,y=1.05) # Set aspect ratio to be equal so that pie is drawn as a circle. plt.axis('equal') plt.show()
def _initialize_instance(cls, obj, profiles, labels, plot_specs, y_log): from matplotlib.font_manager import FontProperties obj._font_properties = FontProperties(family='stixgeneral', size=18) obj._font_color = None obj.profiles = ensure_list(profiles) obj.x_log = None obj.y_log = {} if y_log is not None: for field, log in y_log.items(): field, = obj.profiles[0].data_source._determine_fields([field]) obj.y_log[field] = log obj.y_title = {} obj.label = sanitize_label(labels, len(obj.profiles)) if plot_specs is None: plot_specs = [dict() for p in obj.profiles] obj.plot_spec = plot_specs obj.plots = PlotContainerDict() obj.figures = FigureContainer(obj.plots) obj.axes = AxesContainer(obj.plots) obj._setup_plots() return obj
def __init__(self, data_source, figure_size, fontsize): from matplotlib.font_manager import FontProperties self.data_source = data_source self.ds = data_source.ds self.ts = self._initialize_dataset(self.ds) if iterable(figure_size): self.figure_size = float(figure_size[0]), float(figure_size[1]) else: self.figure_size = float(figure_size) font_path = matplotlib.get_data_path() + '/fonts/ttf/STIXGeneral.ttf' self._font_properties = FontProperties(size=fontsize, fname=font_path) self._font_color = None self._xlabel = None self._ylabel = None self._minorticks = {} self._field_transform = {}
def resizeEvent(self, event): w = event.size().width() h = event.size().height() # Leave a fixed amount for the axes padding = 7.5*FontProperties(size=rcParams['axes.labelsize']).get_size_in_points() posx = padding/w posy = padding/h self.axes.set_position([posx, posy, 0.97-posx, 0.97-posy]) super(MplCanvas, self).resizeEvent(event)
def personal_money(): baidu_current = 2619 baidu_fix = 50000 jd = 19284 lujinsuo = 43998 icbc = 455 cmb = 77 zhifubao = 0 stock_ht = 53200 stock_gj = 19112 fund = 3515 qq = 1000 X = [baidu_current + baidu_fix, jd, lujinsuo, icbc, cmb, stock_ht, stock_gj, fund, qq] labels = [u'??', u'??', u'???', u'??', u'??', u'??', u'??', u'??', u'QQ'] plt.figure() plt.subplot(2, 1, 1) p = plt.pie(X, labels=labels, autopct='%1.1f' ) print p # plt.show() print p[1] # ?????? for font in p[1]: font.set_fontproperties(mpl.font_manager.FontProperties( fname='C:/Windows/winsxs/amd64_microsoft-windows-font-truetype-simfang_31bf3856ad364e35_6.1.7600.16385_none_e417159f3b4eb1b7/simfang.ttf')) plt.subplot(2, 1, 2) x2 = [baidu_fix + baidu_current + jd + lujinsuo + icbc + cmb + qq, fund + stock_gj + stock_ht] print x2 labels2 = [u'??', u'??'] p2 = plt.pie(x2, labels=labels2,autopct='%1.1f') for font2 in p2[1]: font2.set_fontproperties(mpl.font_manager.FontProperties( fname='C:/Windows/winsxs/amd64_microsoft-windows-font-truetype-simfang_31bf3856ad364e35_6.1.7600.16385_none_e417159f3b4eb1b7/simfang.ttf')) plt.show()
def ConvergencePlot(cost): """ Monitors convergence. Parameters: ---------- :param dict cost: mean and best cost over cycles/generations as returned by an optimiser. """ font = FontProperties(); font.set_size('larger'); labels = ["Best Cost Function", "Mean Cost Function"] plt.figure(figsize=(12.5, 4)); plt.plot(range(len(cost["best"])), cost["best"], label=labels[0]); plt.scatter(range(len(cost["mean"])), cost["mean"], color='red', label=labels[1]); plt.xlabel("Iteration #"); plt.ylabel("Value [-]"); plt.legend(loc="best", prop = font); plt.xlim([0,len(cost["mean"])]); plt.grid(); plt.show(); # ---- END
def set_fontprops(): fontP = FontProperties() fontP.set_size('small') return fontP
def plot_stoch_indicator(price,sma,stochk,file_name): plt.clf() fig = plt.figure() ax = fig.add_subplot(211) ax.set(title = 'AAPL with Stochastic Indicator') ax.plot(price,label = 'AAPL Price') ax.plot(sma,label = 'SMA(21)') #ax.plot(upper_band, label = 'upper_band', color='r') #ax.plot(bottom_band,label = 'bottom_band',color='r') ax.set_ylabel('Price') #ax.set_ylim([0,2]) #start, end = ax.get_xlim() #ax.xaxis.set_ticks(np.arange(start,end,90)) L = plt.legend() L.get_texts()[0].set_text('AAPL Price') L.get_texts()[0].set_text('SMA(21)') #L.get_texts()[1].set_text('Upper_band') #L.get_texts()[2].set_text('Lower_band') ax.tick_params(labelbottom='off') ax.legend(loc = 'upper center',bbox_to_anchor = (0.55,1.0), prop = {'size':7}) ###create font properties #fontP = FontProperties() #fontP.set_size('small') #plt.legend([ax], "title",prop = fontP) ax1 = fig.add_subplot(212) ax1.plot(stochk,label = 'stochk',color = 'r') #ax1.plot(stochd,label = 'stochd', color = 'green') ax1.set_ylabel('Stochastic Oscillator') ax1.set_xlabel('Date') ax1.axhline(20.0, color = 'black') ax1.axhline(80.0, color = 'black') #start1, end1 = ax1.get_xlim() #ax1.xaxis.set_ticks(np.arange(start,end,90)) fig.subplots_adjust(hspace=0.05)#,left = 0.2, right = 1.0, top = 0.2, bottom = 0.1) plt.xticks(rotation=30) plt.savefig(file_name) #plt.show()
def plot_bollinger_band_indicator(price,sma,upper_band, bottom_band,bbp, file_name): plt.clf() fig = plt.figure() ax = fig.add_subplot(211) ax.set(title = 'AAPL with Bollinger Band Indicator') ax.plot(price,label = 'AAPL Price') ax.plot(sma,label = 'SMA(21)') ax.plot(upper_band, label = 'upper_band', color='r') ax.plot(bottom_band,label = 'bottom_band',color='r') ax.set_ylabel('Price') #ax.set_ylim([0,2]) #start, end = ax.get_xlim() #ax.xaxis.set_ticks(np.arange(start,end,90)) L = plt.legend() L.get_texts()[0].set_text('AAPL Price') L.get_texts()[1].set_text('SMA(21)') L.get_texts()[2].set_text('Upper_band') L.get_texts()[3].set_text('Lower_band') ax.tick_params(labelbottom='off') ax.legend(loc = 'upper center',bbox_to_anchor = (0.55,1.0), prop = {'size':7}) ###create font properties #fontP = FontProperties() #fontP.set_size('small') #plt.legend([ax], "title",prop = fontP) ax1 = fig.add_subplot(212) ax1.plot(bbp,label = 'bbp',color = 'r') ax1.set_ylabel('Bollinger Band (%BB)') ax1.set_xlabel('Date') ax1.axhline(0.0, color = 'black') ax1.axhline(1.0, color = 'black') fig.subplots_adjust(hspace=0.1) #start, end = ax.get_xlim() #ax1.xaxis.set_ticks(np.arange(start,end,90)) plt.xticks(rotation=30) plt.savefig(file_name) #plt.show()
def plot_rsi_indicator(price,sma,rsi, file_name): plt.clf() fig = plt.figure() ax = fig.add_subplot(211) ax.set(title = 'AAPL with RSI Indicator') ax.plot(price,label = 'AAPL Price') ax.plot(sma,label = 'SMA(21)') #ax.plot(upper_band, label = 'upper_band', color='r') #ax.plot(bottom_band,label = 'bottom_band',color='r') ax.set_ylabel('Price') #ax.set_ylim([0,2]) #start, end = ax.get_xlim() #ax.xaxis.set_ticks(np.arange(start,end,90)) L = plt.legend() L.get_texts()[0].set_text('AAPL Price') L.get_texts()[1].set_text('SMA(21)') #L.get_texts()[1].set_text('Upper_band') #L.get_texts()[2].set_text('Lower_band') ax.tick_params(labelbottom='off') ax.legend(loc = 'upper center',bbox_to_anchor = (0.55,1.0), prop = {'size':7}) ###create font properties #fontP = FontProperties() #fontP.set_size('small') #plt.legend([ax], "title",prop = fontP) ax1 = fig.add_subplot(212) ax1.plot(rsi,label = 'rsi',color = 'r') ax1.set_ylabel('Relative Strength Index') ax1.set_xlabel('Date') ax1.axhline(30.0, color = 'black') ax1.axhline(70.0, color = 'black') #start1, end1 = ax1.get_xlim() #ax1.xaxis.set_ticks(np.arange(start,end,90)) fig.subplots_adjust(hspace=0.1) plt.xticks(rotation=30) plt.savefig(file_name) #plt.show()
def surface_plot(figure,X,Y,Z,color1,color2=None,xlabel="",ylabel="",zlabel="",alpha=1.0,linewidth=3,label=""): from mpl_toolkits.mplot3d import axes3d from matplotlib.colors import LinearSegmentedColormap if color2 is None: color2 = color1 cdict = {'red': ((0.0, color1[0], color1[0]),(1.0, color2[0], color2[0])), 'green': ((0.0, color1[1], color1[1]),(1.0, color2[1], color2[1])), 'blue': ((0.0, color1[2], color1[2]),(1.0, color2[2], color2[2]))} cmap = LinearSegmentedColormap('CMap', cdict) font = fm.FontProperties(family = 'Trebuchet', weight ='light') figure.patch.set_facecolor('white') axes = figure.add_subplot(111,projection='3d') if X.ndim<2: X = np.tile(np.array(X),(Y.shape[-1],1)).transpose() if Y.ndim<2: Y = np.tile(np.array(Y),(X.shape[0],1)) axes.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cmap,alpha=alpha,linewidth=linewidth,label=label) 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) axes.set_zlabel(zlabel, fontproperties=font, size=10, style='italic') axes.set_zlim(Z.min(),Z.max()) axes.set_zticklabels(axes.get_zticks(),fontproperties=font, size=12)
def density_plot(figure,X,Y,color,xlabel="",ylabel="",n_points=10,linewidth=1,marker_size=40.,alpha=1.0,label=""): font = fm.FontProperties(family = 'Trebuchet', weight ='light') #font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light') figure.patch.set_facecolor('white') axes = figure.add_subplot(111) # axes.plot(X,Y,linewidth=1,color=tuple(color2),alpha=0.2) # ratios = (Y-Y.min())/(Y.max()-Y.min()) # X_min = X.mean()-3*X.std() # X_max = X.mean()+3*X.std() X_min = np.percentile(X,100/n_points) X_max = np.percentile(X,100 - 100/n_points) Y_min = np.percentile(Y,100/n_points) # Y_min = Y.mean()-3*Y.std() Y_max = np.percentile(Y,100 - 100/n_points) X_grid = np.linspace(X_min,X_max,n_points) Y_grid = np.linspace(Y_min,Y_max,n_points) X_sampled = X_grid[vq(X,X_grid)[0]] Y_sampled = Y_grid[vq(Y,Y_grid)[0]] point_density = {} for x in np.unique(X_sampled): point_count = nd.sum(np.ones_like(np.where(X_sampled==x)),Y_sampled[np.where(X_sampled==x)],index=np.unique(Y_sampled)) for i,y in enumerate(np.unique(Y_sampled)): point_density[(x,y)] = point_count[i]/len(Y) point_area = np.array([np.pi*10.0*marker_size*point_density[(x,y)]/np.array(point_density.values()).max() for x,y in zip(X_sampled,Y_sampled)]) #colors = np.random.rand(len(X)) colors = np.array([point_density[(x,y)]/np.array(point_density.values()).max() * color for x,y in zip(X_sampled,Y_sampled)]) colors += np.array([(1-point_density[(x,y)]/np.array(point_density.values()).max()) * np.ones(3) for x,y in zip(X_sampled,Y_sampled)]) axes.scatter(X_sampled,Y_sampled,s=point_area,c=colors,linewidth=linewidth,alpha=alpha,label=label) axes.set_xlim(X_min,X_max) axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic') axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12) axes.set_ylim(Y_min,Y_max) axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic') axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
def smooth_plot(figure,X,Y,color1,color2,xlabel="",ylabel="",filled=False,n_points=400,smooth_factor=1.0,spline_order=3,linewidth=3,alpha=1.0,label=""): """ """ X_smooth = np.linspace(X.min(),X.max(),n_points) tck = splrep(X,Y,s=smooth_factor,k=spline_order) Y_smooth = splev(X_smooth,tck,der=0) font = fm.FontProperties(family = 'Trebuchet', weight ='light') #font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light') figure.patch.set_facecolor('white') axes = figure.add_subplot(111) axes.plot(X,Y,linewidth=1,color=tuple(color2),alpha=0.2) if filled: axes.fill_between(X_smooth,Y_smooth,0,color=color2,alpha=0.1) for i in xrange(100): color = tuple(color1*(1.0-i/100.0) + color2*(i/100.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) 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.set_xlim(X.min(),X.max()) axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic') axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12) if '%' in ylabel: axes.set_ylim(0,np.minimum(2*Y.max(),100)) axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic') axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
def violin_plot(figure,X,data,colors,xlabel="",ylabel="",n_points=400,violin_width=None,linewidth=3,marker_size=20): font = fm.FontProperties(family = 'Trebuchet', weight ='light') #font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light') figure.patch.set_facecolor('white') axes = figure.add_subplot(111) if violin_width is None: if len(X)>1: violin_width = ((np.array(X)[1:] - np.array(X)[:-1]).mean())/3. else: violin_width = 0.33 for x in xrange(len(X)): color = colors[x] Y = gaussian_kde(data[x]) D_smooth = np.linspace(np.percentile(Y.dataset,1),np.percentile(Y.dataset,99),n_points) Y_smooth = Y.evaluate(D_smooth) Y_smooth = violin_width*Y_smooth/Y_smooth.max() axes.fill_betweenx(D_smooth,X[x],X[x]+Y_smooth,facecolor=color,alpha=0.1) axes.fill_betweenx(D_smooth,X[x],X[x]-Y_smooth,facecolor=color,alpha=0.1) axes.plot(X[x]+Y_smooth,D_smooth,color=color,linewidth=linewidth,alpha=0.8) axes.plot(X[x]-Y_smooth,D_smooth,color=color,linewidth=linewidth,alpha=0.8) axes.plot([X[x]-Y_smooth[0],X[x]+Y_smooth[0]],[D_smooth[0],D_smooth[0]],color=color,linewidth=linewidth,alpha=0.8) axes.plot([X[x]-Y_smooth[-1],X[x]+Y_smooth[-1]],[D_smooth[-1],D_smooth[-1]],color=color,linewidth=linewidth,alpha=0.8) axes.plot(X[x]-Y_smooth,D_smooth,color=color,linewidth=linewidth,alpha=0.8) axes.plot(X[x],np.percentile(data[x],50),'o',markersize=marker_size,markeredgewidth=linewidth,color=color) axes.plot([X[x],X[x]],[np.percentile(data[x],25),np.percentile(data[x],75)],color=color,linewidth=2*linewidth,alpha=0.5) axes.set_xlim(min(X)-1,max(X)+1) axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic') axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12) axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic') axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
def box_plot(figure,X,data,colors,xlabel="",ylabel="",box_width=None,linewidth=3,marker_size=20,alpha=1): font = fm.FontProperties(family = 'Trebuchet', weight ='light') #font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light') figure.patch.set_facecolor('white') axes = figure.add_subplot(111) if box_width is None: if len(X)>1: box_width = ((np.array(X)[1:] - np.array(X)[:-1]).mean())/3. else: box_width = 0.33 for x in xrange(len(X)): color = colors[x] box_color = np.array(color)/2. axes.fill_between([X[x]-box_width,X[x]+box_width],[np.percentile(data[x],75),np.percentile(data[x],75)],[np.percentile(data[x],25),np.percentile(data[x],25)],facecolor=color,alpha=alpha/2.) axes.plot([X[x]-box_width,X[x]+box_width],[np.percentile(data[x],50),np.percentile(data[x],50)],color=box_color,linewidth=linewidth,alpha=(alpha+1)/2) axes.plot([X[x]-box_width,X[x]+box_width],[np.percentile(data[x],25),np.percentile(data[x],25)],color=box_color,linewidth=linewidth/2.,alpha=alpha) axes.plot([X[x]-box_width,X[x]+box_width],[np.percentile(data[x],75),np.percentile(data[x],75)],color=box_color,linewidth=linewidth/2.,alpha=alpha) axes.plot([X[x]-box_width,X[x]-box_width],[np.percentile(data[x],25),np.percentile(data[x],75)],color=box_color,linewidth=linewidth/2.,alpha=alpha) axes.plot([X[x]+box_width,X[x]+box_width],[np.percentile(data[x],25),np.percentile(data[x],75)],color=box_color,linewidth=linewidth/2.,alpha=alpha) axes.plot([X[x],X[x]],[np.percentile(data[x],25),np.percentile(data[x],10)],color=box_color,linewidth=linewidth/3.,alpha=alpha) axes.plot([X[x],X[x]],[np.percentile(data[x],75),np.percentile(data[x],90)],color=box_color,linewidth=linewidth/3.,alpha=alpha) axes.plot([X[x]-box_width/4.,X[x]+box_width/5.],[np.percentile(data[x],10),np.percentile(data[x],10)],color=box_color,linewidth=linewidth/2.,alpha=alpha) axes.plot([X[x]-box_width/4.,X[x]+box_width/5.],[np.percentile(data[x],90),np.percentile(data[x],90)],color=box_color,linewidth=linewidth/2.,alpha=alpha) # axes.plot(X[x],np.percentile(data[x],50),'o',markersize=np.pi*np.power(box_width/2.,2.),markeredgewidth=linewidth/2.,color=color) outliers = [d for d in data[x] if (d < np.percentile(data[x],10)) or (d > np.percentile(data[x],90))] x_outliers = [X[x] for d in outliers] axes.scatter(x_outliers, outliers, s=marker_size/3.,c=color,linewidth=0,alpha=alpha/2.) axes.set_xlim(min(X)-1,max(X)+1) axes.set_xlabel(xlabel,fontproperties=font, size=10, style='italic') axes.set_xticklabels(axes.get_xticks(),fontproperties=font, size=12) axes.set_ylabel(ylabel, fontproperties=font, size=10, style='italic') axes.set_yticklabels(axes.get_yticks(),fontproperties=font, size=12)
def init_font_matplotlib_qt(self): ''' Initialize font name list QFontComboBox. Also adds font from matplotlib default fonts ''' # Font database of qt self.qtFontDatabase = QFontDatabase() # Getting path of matplotlib ttf directory mplDataPath = mpl.rcParams['datapath'] mplFontPath = os.path.join(mplDataPath, 'fonts') mplTtfFontPath = os.path.join(mplFontPath, 'ttf') # Building ttf files list mplTtfList = [] for f in os.listdir(mplTtfFontPath): if f.endswith('.ttf'): mplTtfList.append(os.path.join(mplTtfFontPath, f)) # Getting name of each font from ttf files mplFontNameList = [mplFontManager.FontProperties(fname=fname).get_name() for fname in mplTtfList] # Getting name of each font from qt font database qtFontNameListQtype = self.qtFontDatabase.families() qtFontNameList = [ str(qtFont) for qtFont in qtFontNameListQtype ] # Comparing and adding matplotlib font to qt font database for i in range(len(mplFontNameList)): matched = False for qtFont in qtFontNameList: if str(qtFont) == mplFontNameList[i]: matched = True if not matched: self.qtFontDatabase.addApplicationFont(mplTtfList[i])
def is_font_exist_in_mpl(self, fontname): result = None result = mplFontManager.findfont(mplFontManager.FontProperties(family=fontname)) if mplFontManager.FontProperties(fname=result).get_name() == fontname: return True else: return False
def DrawTitle(m, title, headtxt): if m is plt: if title.mtitleposition is None: for desc in title.descs: fontfile = r"C:\WINDOWS\Fonts\{0}".format(desc.font['family']) if not os.path.exists(fontfile): font = FontProperties(size=desc.font['fontsize'], weight=desc.font['weight']) else: font = FontProperties(fname=fontfile, size=desc.font['fontsize'], weight=desc.font['weight']) plt.text(desc.pos[0], desc.pos[1], desc.text, # size=desc.font['fontsize'], weight=desc.font['weight'], color=desc.font['color'], fontdict=desc.font, fontproperties=font, rotation=0, ha='left', va='top') else: if title.mtitleposition == [0, 0]: plt.title(headtxt, fontdict={'fontsize': 14}) else: plt.text(title.mtitleposition[0], title.mtitleposition[1], headtxt, size=14, weight='bold', # color='blue', # fontdict=desc.font, # fontproperties=font, rotation=0, ha='left', va='top') else: plt.title(headtxt)
def GetFontProperties(font): fontfile = r"C:\WINDOWS\Fonts\{0}".format(font['family']) if not os.path.exists(fontfile): fp = FontProperties(family=font['family'], weight=font['weight'], size=font['size']) else: fp = FontProperties(fname=fontfile, weight=font['weight'], size=font['size']) return fp
def Display(curvelist): """ Take a list of curve and plot it according to its type @type curvelist: list of curve @param curvelist: list of curve for plotting @todo: improve the display with legend, color... """ plt.figure(figsize=(12,8)) # sets figure size axes = plt.gca() # Something for astronomers only : we invert the y axis direction ! axes.set_ylim(axes.get_ylim()[::-1]) # Astronomers like minor tick marks : minorxLocator = MultipleLocator(100) for curve in curvelist: if curve.type=="purelightcurve": plt.plot(linspace(0,curve.length,curve.length*curve.res),curve.data) if curve.type=="simlightcurve": if curve.name=="A": plt.plot(np.linspace(0,curve.originalcurve.length,curve.originalcurve.length*curve.originalcurve.res),curve.originalcurve.data+curve.dmag,color="black",label="Original curve") plt.errorbar(curve.datatime,curve.datamagoff(),curve.dataerr,ls='None',marker='.',ecolor="#BBBBBB", color=curve.plotcolor,label=str(curve.name)+str(curve.shift)) plt.plot(np.linspace(0,curve.originalcurve.length,curve.originalcurve.length*curve.originalcurve.res),curve.mlcurve.data+curve.dmag,color=curve.plotcolor)#,label="microlensing for "+str(curve.name)) plt.xlabel('time [j]') plt.ylabel('Magnitude ') plt.legend( numpoints = 1, prop = fm.FontProperties(size = 10)) plt.show()
def main(): dataset = VOCBboxDataset(year='2007', split='test') models = [ ('Faster R-CNN', FasterRCNNVGG16(pretrained_model='voc07')), ('SSD300', SSD300(pretrained_model='voc0712')), ('SSD512', SSD512(pretrained_model='voc0712')), ] indices = [29, 301, 189, 229] fig = plot.figure(figsize=(30, 30)) for i, idx in enumerate(indices): for j, (name, model) in enumerate(models): img, _, _ = dataset[idx] bboxes, labels, scores = model.predict([img]) bbox, label, score = bboxes[0], labels[0], scores[0] ax = fig.add_subplot( len(indices), len(models), i * len(models) + j + 1) vis_bbox( img, bbox, label, score, label_names=voc_bbox_label_names, ax=ax ) # Set MatplotLib parameters ax.set_aspect('equal') if i == 0: font = FontProperties() font.set_family('serif') ax.set_title(name, fontsize=35, y=1.03, fontproperties=font) plot.axis('off') plot.tight_layout() plot.show()
def getFont(): return fm.FontProperties(fname="c:/windows/fonts/simsun.ttc") ########################################################################
def DrawTs(pl, ts=[], lines = None, title="", high=[], low=[],mid=[], save_file=False,legends=None): """?????, ts: closes, save_file: ?????????""" pl.figure legend = [] if len(ts)>0: pl.plot(ts) legend.append('ts') if len(high)>0: pl.plot(high) legend.append('high') if len(low)>0: pl.plot(low) legend.append('low') if len(mid)>0: pl.plot(mid) legend.append('mid') prop = fm.FontProperties(fname="c:/windows/fonts/simsun.ttc") if title != "": pl.title(title, fontproperties=prop) if lines != None: i = lines if i>=len(ts): i = len(ts)-1 pl.plot([i,i], [ts[i]-ts[i]*0.1, ts[i]+ts[i]*0.1], 'g') legend.append('lines') if legends is not None: legend = legends pl.legend(legend, loc='upper left') if save_file: fname = 't3.png' pl.savefig(fname) return fname pl.show() pl.close()
def DrawScatt(pl, x,y, title=''): pl.figure prop = fm.FontProperties(fname="c:/windows/fonts/simsun.ttc") if title != "": pl.title(title, fontproperties=prop) pl.scatter(x,y) pl.ylabel(u"???", fontproperties=prop) pl.xlabel(u"????(?)", fontproperties=prop) pl.show() pl.close()
def __init__(self, fontPath): if not os.path.exists(self.imgDir): os.mkdir(self.imgDir) self.client = client self.coll = self.client[dbName][collName] self.prop = FontProperties(fname=fontPath) logging.info('ActivityInfo initialized.')
def getChineseFont(): return FontProperties(fname='/Users/luoyi/Downloads/msyh.ttf')
def rasterize_kanji(kanji, weight, output_file): kanji = kanji[0:4] # strip extra stuff like footnotes off kanji prop = fm.FontProperties(fname="ipam.ttc", size=70) plt.figure(figsize=(1, 1)) plt.text(0, 0, kanji, ha='center', va='center', fontproperties=prop) plt.xlim(-0.4, 0.1) plt.ylim(-0.1, 0.1) plt.axis("off") #plt.savefig(output_file) #image = scipy.misc.imread(output_file, flatten=True) buf = io.BytesIO() plt.savefig(buf, format="png") buf.seek(0) image = PIL.Image.open(buf).convert(mode="L") buf.close() image = np.asarray(image, dtype=np.uint8) plt.close() image = scipy.misc.imresize(image, [kanji_height, kanji_width]) image = skimage.img_as_float(image).astype(np.float32) image = 1.0 - image # make the background black and the text white if (weight == "bold"): erosion_size = 5 elif (weight == "normal"): erosion_size = 3 else: erosion_size = 0 if (erosion_size > 0): kernel = np.ones((erosion_size, erosion_size), np.float32) image = cv2.dilate(image, kernel, iterations=1) scipy.misc.imsave(output_file, (1.0 - image)) return image
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")])
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)
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()
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)