def renderFigure(self, fig): def genMarkup(chartFigure): return self.env.from_string(""" {0} {{%for message in messages%}} <div>{{{{message}}}}</div> {{%endfor%}} """.format(chartFigure) ).render(messages=self.messages) if not self.useMpld3: import base64 try: from io import BytesIO as pngIO except ImportError: from StringIO import StringIO as pngIO png=pngIO() plt.savefig(png, pad_inches=0.05, bbox_inches='tight', dpi=self.getDPI()) try: return( genMarkup(""" <center><img style="max-width:initial !important" src="data:image/png;base64,{0}" class="pd_save"></center> """.format(base64.b64encode(png.getvalue()).decode("ascii")) ) ) finally: png.close() else: mpld3.enable_notebook() try: return genMarkup(mpld3.fig_to_html(fig)) finally: mpld3.disable_notebook()
def renderFigure(self, fig): def genMarkup(chartFigure): return self.env.from_string(""" {0} {{%for message in messages%}} <div>{{{{message}}}}</div> {{%endfor%}} """.format(chartFigure)).render(messages=self.messages) if not self.useMpld3: import base64 try: from io import BytesIO as pngIO except ImportError: from StringIO import StringIO as pngIO png = pngIO() plt.savefig(png, pad_inches=0.05, bbox_inches='tight', dpi=self.getDPI()) try: return (genMarkup(""" <center><img style="max-width:initial !important" src="data:image/png;base64,{0}" class="pd_save"></center> """.format( base64.b64encode(png.getvalue()).decode("ascii")))) finally: png.close() else: mpld3.enable_notebook() try: return genMarkup(mpld3.fig_to_html(fig)) finally: mpld3.disable_notebook()
def renderFigure(self, fig, dialogBody): if self.options.get("staticFigure","false") is "true": import StringIO png=StringIO.StringIO() plt.savefig(png) self._addHTMLTemplate("mpld3Chart.html", mpld3Figure="""<img src="data:image/png;base64,{0}">""".format(png.getvalue().encode('base64')), optionsDialogBody=dialogBody) plt.close(fig) else: mpld3.enable_notebook() self._addHTMLTemplate("mpld3Chart.html", mpld3Figure=mpld3.fig_to_html(fig), optionsDialogBody=dialogBody) plt.close(fig) mpld3.disable_notebook()
def mplPlot2D(self): #newdata=Transpose(ww.data) mpld3.disable_notebook() from matplotlib.ticker import MaxNLocator from matplotlib.colors import Normalize z=self.data[2] #normLev=Normalize(self.vmin,self.vmax) #levels = MaxNLocator(nbins=self.numBins).tick_values(z.min(), z.max()) z[z>self.vmax]=numpy.nan z[z<self.vmin]=numpy.nan #plt.pcolor(self.data[0],self.data[1],self.data[2],vmin=self.vmin, vmax=self.vmax) plt.pcolor(self.data[0],self.data[1],self.data[2], vmin=self.vmin, vmax=self.vmax, )
def mplPlot2D(self): #newdata=Transpose(ww.data) mpld3.disable_notebook() from matplotlib.ticker import MaxNLocator from matplotlib.colors import Normalize z = self.data[2] #normLev=Normalize(self.vmin,self.vmax) #levels = MaxNLocator(nbins=self.numBins).tick_values(z.min(), z.max()) z[z > self.vmax] = numpy.nan z[z < self.vmin] = numpy.nan #plt.pcolor(self.data[0],self.data[1],self.data[2],vmin=self.vmin, vmax=self.vmax) plt.pcolor( self.data[0], self.data[1], self.data[2], vmin=self.vmin, vmax=self.vmax, )
def d3(): import mpld3 mpld3.enable_notebook() yield mpld3.disable_notebook()
#Computing the Univariate F-score for feature selection from sklearn.feature_selection import SelectKBest, f_classif # import the feature selection method N_features = 19 # select the number of features Nfl = CME_data.shape[0] Nnofl = no_CME_data.shape[0] yfl = np.ones(Nfl) ynofl = np.zeros(Nnofl) selector = SelectKBest(f_classif, k=N_features) # k is the number of features selector.fit(np.concatenate((CME_data, no_CME_data), axis=0), np.concatenate((yfl, ynofl), axis=0)) scores = selector.scores_ print scores #interpret the scores in plot: mpld3.disable_notebook() plt.clf() order = np.argsort(scores) orderedsharps = [sharps[i] for i in order] y_pos2 = np.arange(19) plt.barh(y_pos2, sorted(scores / np.max(scores)), align='center') plt.ylim((-1, 19)) plt.yticks(y_pos2, orderedsharps) plt.xlabel('Normalized Fisher Score', fontsize=15) plt.title('Ranking of SHARP features', fontsize=15) fig = plt.gcf() fig.set_size_inches(8, 10) fig.savefig('sharp_ranking_48hours.png', bbox_inches='tight') plt.show() #Pearson linear correlation coefficients
len(top_births.columns) # <codecell> # how to get the most popular name of all time in top_births? most_common_names = top_births.sum() most_common_names.sort(ascending=False) most_common_names.head() # <codecell> # as of mpl v 0.1 (2014.03.04), the name labeling doesn't work -- so disble mpld3 for this figure mpld3.disable_notebook() plt.figure() most_common_names[:50][::-1].plot(kind='barh', figsize=(10,10)) # <codecell> # turn mpld3 back on mpld3.enable_notebook() # <headingcell level=1> # all_births pivot table # <codecell>
def plot_optimization_evolution_2d(evolution_data, *args, obj_func=None, **kwargs): """For a given population, plot their positions in solution space in 2d over time. Arguments --------- evolution_data: list over iterations where each entry is a dict of population members holding their 2d positions as a list xlims (optional): list of lower and upper x lim for plot ylims (optional): list of lower and upper y lim for plot obj_func: name of the objective function to contour plot in the background """ mpld3.enable_notebook() fig, ax = viz_utils.setup_figure_1ax(x_label='x position', y_label='y position', size=(8, 8), shrink_ax=False) if obj_func: if obj_func not in OBJ_FUNCS: raise NotImplementedError( f'{obj_func} is not implemented for plotting. ' f'Only {list(OBJ_FUNCS.keys())} can be plotted.\n' f'Feel free to implement them in python :)') mpld3.disable_notebook( ) # contour plots cannot be json serialized so we have to switch of d3 mode min_x, max_x, min_y, max_y = viz_utils.get_min_max_of_evolution_data( evolution_data) x_list = np.linspace(min_x, max_x, 100) y_list = np.linspace(min_y, max_y, 100) x_mesh, y_mesh = np.meshgrid(x_list, y_list) z_mesh = OBJ_FUNCS[obj_func](np.vstack( [x_mesh.ravel(), y_mesh.ravel()])).reshape((100, 100)) ax.contourf( x_mesh, y_mesh, z_mesh, [rosenbrock(np.array([k, k])) for k in np.linspace(1, 20, 50)], cmap='jet', locator=ticker.LogLocator(), alpha=0.1) for iter_idx, step_dict in enumerate(evolution_data): if iter_idx == 0: color = 'black' else: color = viz_utils.get_color_from_cm(cm.hot, 1, len(evolution_data), iter_idx + 1) x = [pos[0] for pos in step_dict.values()] y = [pos[1] for pos in step_dict.values()] ax.plot(x, y, '.', color=color, alpha=0.7, markeredgewidth=0.0) if 'xlims' in kwargs: ax.set_xlim(kwargs['xlims']) if 'ylims' in kwargs: ax.set_ylim(kwargs['ylims']) if 'title' in kwargs: ax.set_title(kwargs['title']) return fig, ax