def main(): fig, ax = plt.subplots() line, = ax.plot([0, 1, 3, 8, 5], '-', lw=5) plugins.connect(fig, plugins.LineLabelTooltip(line, ['Line A'])) ax.set_title('Line with Tooltip') return fig
def fgsm_attack(request): #标准化数据 input = ( (255 - np.array(eval(request.POST.get('inputs')), dtype=np.float32)) / 255.0).reshape(1, 28, 28, 1) X_adv = make_fgsm(sess, env, input, epochs=12, eps=0.02).tolist() # print(X_adv[0]) X_tmp = np.empty((10, 28, 28)) X_tmp[0] = np.squeeze(X_adv[0]) # print(X_tmp[0]) fig = plt.figure(figsize=(1, 1.2)) gs = gridspec.GridSpec(1, 1, wspace=0.05, hspace=0.05) ax = fig.add_subplot(gs[0, 0]) # 分别画子图 ax.imshow(X_tmp[0], cmap='gray', interpolation='none') # 展示预测错的对抗样本 ax.set_xticks([]) ax.set_yticks([]) plugins.connect(fig, plugins.MousePosition(fontsize=14)) # mpld3.show() os.makedirs('img', exist_ok=True) plt.savefig('img/fgsm_mnist.png') # return HttpResponse(json.dumps(X_adv)) # print(mpld3.fig_to_html(fig)) return HttpResponse(mpld3.fig_to_html(fig))
def plot_page_mpld3(df, columns, request, field=None, value=None): if request.method == 'POST': # Something is being submitted x1 = str(request.form['x1']) x2 = str(request.form['x2']) y1 = str(request.form['y1']) y2 = str(request.form['y2']) z = str(request.form['z']) for requested_col in {x1, x2, y1, y2, z}: if requested_col not in columns: return redirect(url_for('sd')) else: x1, x2, y1, y2, z = 'days_old', 'los', 'los', 'los', 'days_old' if field and value is None: field = 'all fields' value = 'all values' # Does not work with NaN values! so we must remove rows with NaN values df = df.loc[:, {x1, x2, y1, y2, z}].dropna(axis=0) fig, ax = plt.subplots(2, 2, figsize=(12, 8), sharex='col', sharey='row') points = ax[0, 0].scatter(df[x1], df[y1], c=df[z], alpha=0.6) points = ax[1, 0].scatter(df[x1], df[y2], c=df[z], alpha=0.6) points = ax[0, 1].scatter(df[x2], df[y1], c=df[z], alpha=0.6) points = ax[1, 1].scatter(df[x2], df[y2], c=df[z], alpha=0.6) ax[0, 0].set_ylabel(y1) ax[0, 0].set_xlabel(x1) ax[1, 0].set_ylabel(y2) ax[1, 0].set_xlabel(x1) ax[1, 1].set_ylabel(y2) ax[1, 1].set_xlabel(x2) # ax[1, 0].set_title('Filtered by {} of {}'.format(field, value)) # ax[1, 1].set_title('Filtered by {} of {}'.format(field, value)) # ax[0, 0].set_title('Filtered by {} of {}'.format(field, value)) size = df.shape[0] ax[0, 1].set_title('all plots filtered by {} with {} of size: {}'.format( field, value, str(size))) ax[0, 1].set_ylabel(y1) ax[0, 1].set_xlabel(x2) for axe in ax.flatten(): for tk in axe.get_yticklabels(): tk.set_visible(True) for tk in axe.get_xticklabels(): tk.set_visible(True) ax[0, 0].grid(color='grey', linestyle='-', linewidth=2) ax[0, 1].grid(color='grey', linestyle='-', linewidth=2) ax[1, 0].grid(color='grey', linestyle='-', linewidth=2) ax[1, 1].grid(color='grey', linestyle='-', linewidth=2) plugins.connect(fig, plugins.LinkedBrush(points)) plot = fig_to_html(fig) return render_template('plot_mpld3.html', plot=plot, columns=columns, x1=x1, x2=x2, y1=y1, y2=y2, z=z)
def draw_spectrum(spectrum, dummy=False): rmf = pf.open('rmf_62bands.fits') src_spectrum = spectrum[8].data E_min = rmf[3].data['E_min'] E_max = rmf[3].data['E_max'] msk = src_spectrum['RATE'] > 0. y = src_spectrum['RATE'] / (E_max - E_min) x = (E_max + E_min) dx = np.log10(np.e) * (E_max - E_min) / x x = np.log10(x) dy = src_spectrum['STAT_ERR'] / (E_max - E_min) dy = np.log10(np.e) * dy / y y = np.log10(y) fig, ax = plt.subplots(figsize=(4, 2.8)) ax.set_xlabel('log(E) keV') ax.set_ylabel('log(counts/s/keV)') ax.errorbar(x[msk], y[msk], yerr=dy[msk] * 0.5, xerr=dx[msk] * 0.5, fmt='o') #print (x,y,dy) plugins.connect(fig, plugins.MousePosition(fontsize=14)) return mpld3.fig_to_dict(fig)
def main(): fig, ax = plt.subplots() points = ax.plot(range(10), 'o', ms=20) plugins.connect(fig, plugins.PointLabelTooltip(points[0], location="top left")) return fig
def hello(): df = pd.DataFrame(data=np.random.randn(20, 8), columns=list('abcdefgh')) fig, ax = plt.subplots() ax.set_xlabel('a') ax.set_ylabel('b') ax.set_title('hoge') points = ax.plot(df.a, df.b, 'o', mec='k', ms=15, mew=1, alpha=.6) labels = [] for i in df.a.items(): label = df.ix[[i[0]], :].T label.columns = ['Data List'] labels.append(str(label.to_html())) tooltip = plugins.PointHTMLTooltip(points[0], labels, voffset=10, hoffset=10, css=get_css()) plugins.connect(fig, tooltip) plugins.connect( fig, JavascriptPlugin(from_api_root('static/plugins/HelloWorld.js'), 'click_info', points[0])) with open(from_api_root('templates/figure.html'), "w") as fw: fw.writelines(mpld3.fig_to_html(fig, figid="figure")) return render_template('hello.html')
def main(): fig, ax = plt.subplots() line, = ax.plot([0, 1, 3, 8, 5], '-', lw=5) plugins.connect(fig, plugins.LineLabelTooltip(line, 'Line A')) ax.set_title('Line with Tooltip') return fig
def create_plot(): fig, ax = plt.subplots() line, = ax.plot([0, 1, 3, 8, 5], '-', lw=5) label = '<h1>Line {}</h1>'.format('A') plugins.connect(fig, plugins.LineHTMLTooltip(line, label)) ax.set_title('Line with HTML Tooltip') return fig
def plot_snr_cmd(self, snr, ax, color='bv', mag='v', add_candidates=True): cmd_search = self.session.query(malchemy.MCPS).\ join(malchemy.SNRNeighbour).join(malchemy.SNRS).\ filter(malchemy.SNRS.id==snr.snr.id) cmd_data = [(item.__getattribute__(color[0]) - item.__getattribute__(color[1]), item.__getattribute__(mag)) for item in cmd_search] data = np.array(cmd_data) H, xedges, yedges = np.histogram2d(data[:,1], data[:,0], bins=100, range=[[16,22],[-1,2]]) extent = [yedges[0], yedges[-1], xedges[-1], xedges[0]] ax.imshow(H, extent=extent, interpolation='nearest', cmap=cm.gray_r, aspect='auto') ax.set_xlabel('Color {0} - {1}'.format(*list(color))) ax.set_ylabel('mag {0}'.format(mag)) if add_candidates: candidate_coord = [(item.mcps.__getattribute__(color[0]) - item.mcps.__getattribute__(color[1]), item.mcps.__getattribute__(mag)) for item in snr.candidates] candidate_coord = np.array(candidate_coord) cand_plot = ax.plot(candidate_coord[:,0], candidate_coord[:,1], 'bo') cand_labels = [str(item) for item in snr.candidates] tooltip = plugins.PointHTMLTooltip(cand_plot[0], cand_labels, voffset=10, hoffset=10) plugins.connect(ax.figure, tooltip) return cand_plot
def doRender(self, handlerId): if self.canRenderChart(handlerId) == False: self._addHTML("Unable to find a numerical column in the dataframe") return mpld3.enable_notebook() fig, ax = plt.subplots() keyFields = self.getKeyFields(handlerId) keyFieldValues = self.getKeyFieldValues(handlerId, keyFields) keyFieldLabels = self.getKeyFieldLabels(handlerId, keyFields) valueFields = self.getValueFields(handlerId) valueFieldValues = self.getValueFieldValueLists(handlerId, keyFields, valueFields) context = self.getMpld3Context(handlerId) options = {"fieldNames":self.getFieldNames(),"aggregationSupported":self.supportsAggregation(handlerId),"aggregationOptions":["SUM","AVG","MIN","MAX","COUNT"]} if (context is not None): options.update(context[1]) dialogBody = self.renderTemplate(context[0], **options) else: dialogBody = self.renderTemplate("baseChartOptionsDialogBody.html", **options) plugins.connect(fig, ChartPlugin(self, keyFieldLabels)) plugins.connect(fig, DialogPlugin(self, handlerId, dialogBody)) self.doRenderMpld3(handlerId, fig, ax, keyFields, keyFieldValues, keyFieldLabels, valueFields, valueFieldValues) self.setChartSize(handlerId, fig, ax) self.setChartGrid(handlerId, fig, ax) self.setChartLegend(handlerId, fig, ax)
def demo(): if request.method == 'POST': # Something is being submitted x1 = str(request.form['x1']) x2 = str(request.form['x2']) y1 = str(request.form['y1']) y2 = str(request.form['y2']) z = str(request.form['z']) else: x1, x2, y1, y2, z = 'teff', 'mass', 'Vmag', 'par', 'logg' df = pd.read_table('stars.csv') columns = df.columns.values df = df.loc[:, list(set([x1, x2, y1, y2, z]))].dropna(axis=0) fig, ax = plt.subplots(2, 2, figsize=(10, 8), sharex='col', sharey='row') points = ax[0, 0].scatter(df[x1], df[y1], c=df[z], alpha=0.6) points = ax[1, 0].scatter(df[x1], df[y2], c=df[z], alpha=0.6) points = ax[0, 1].scatter(df[x2], df[y1], c=df[z], alpha=0.6) points = ax[1, 1].scatter(df[x2], df[y2], c=df[z], alpha=0.6) ax[1, 0].set_xlabel(x1) ax[1, 1].set_xlabel(x2) ax[0, 0].set_ylabel(y1) ax[1, 0].set_ylabel(y2) plugins.connect(fig, plugins.LinkedBrush(points)) plot = fig_to_html(fig) return render_template('plot.html', plot=plot, columns=columns, x1=x1, x2=x2, y1=y1, y2=y2, z=z)
def plot_by_mpld3(dataframe,figsize=(12,6),marker='o',grid=True, alpha_ax=0.3,alpha_plot=0.4,alpha_unsel=0.3,alpha_over=1.5, title=None,xlabel=None,ylabel=None,mode="display",file=None): ## DataFrame 데이터를 이용하여 웹용 D3 chart 스크립트 생성 # plot line + confidence interval fig, ax = plt.subplots(figsize=figsize) ax.grid(grid, alpha=alpha_ax) for key, val in dataframe.iteritems(): l, = ax.plot(val.index, val.values, label=key, marker=marker) ax.plot(val.index,val.values, color=l.get_color(), alpha=alpha_plot) # define interactive legend handles, labels = ax.get_legend_handles_labels() # return lines and labels interactive_legend = plugins.InteractiveLegendPlugin(handles,labels, alpha_unsel=alpha_unsel, alpha_over=alpha_over, start_visible=True) plugins.connect(fig, interactive_legend) if xlabel: ax.set_xlabel(xlabel) if ylabel: ax.set_ylabel(ylabel) if title: ax.set_title(title, size=len(title)+5) ## mode if mode == 'html': # return html script return mpld3.fig_to_html(fig) elif mode == 'save' and file: # save file mpld3.save_html(fig,file) else: # display chart #mpld3.enable_notebook() return mpld3.display()
def gen_html(self, dataset=None, channels=["FSC-A", "SSC-A"]): if not dataset: dataset = self.dataset data = [dataset[i].values for i in channels] fig = plt.figure() ax = fig.add_subplot(111) plot = ax.scatter(data[0], data[1]) plugins.clear(fig) plugins.connect(fig, plugins.LinkedBrush(plot), plugins.ClickSendToBack(plot)) the_html = mpld3.fig_to_html(fig) with open("initialfigure.html", "w") as file: file.write(the_html) o = bs(open("initialfigure.html"), "html.parser") script = str(o.find_all("script")[0]) script_2 = script.replace("<script>", "").replace("</script>", "") with open("the_figure.js", "w") as file: file.write(script_2) with open("the_figure.html", "w") as file: the_html = the_html.replace( script, "<script src='.\\the_figure.js'></script>") file.write(the_html)
def turn_scatter_into_interactive(fig, scatter_plot, df, file_name, figsize=False): from jinja2 import Template, Environment, FileSystemLoader from mpld3 import plugins # file_path = './assets/interactive_plots/'+file_name file_path = './' + file_name env = Environment(loader=FileSystemLoader('./views')) movie_template = env.get_template('movie.jinjia') movies = df.to_dict(orient='records') movie_cards = [ movie_template.render(movie=movie, show_ratings_num=True) for movie in movies ] if figsize: fig.set_size_inches(figsize) else: fig.set_size_inches(8.5, 8.5) plugins.connect( fig, plugins.PointHTMLTooltip(scatter_plot, movie_cards, css=load_css(raw=True))) mpld3.save_html(fig, file_path) button = '''<a class='btn btn-default' style="text-decoration: none;;" href="{0}" target='_blank'> Interactive Scatter Plot</a> '''.format(file_path) return HTML(button)
def create_plot(): fig, ax = plt.subplots() ax.plot([2000, 2050], [1, 2]) ax.set_title('Test ticklabel plugin (should be different than image!)', size=14) plugins.connect(fig, TickFormat()) return fig
def display_comparison_plot_mpld3(t, arr, names, line_styles, title, xtitle, ytitle, ylim, figname): # Function used to generate interactive d3 plots in html f, ax = plt.subplots() lines = [] for i in np.arange(0, len(names)): l, = ax.plot(t, arr[:, i], label=names[i], lw=3, ls=line_styles[i], alpha=0.2) lines.append(l) ax.set_xlabel(xtitle) ax.set_ylabel(ytitle) ax.set_title(title) ax = plt.gca() ax.set_ylim(ylim) ax.grid() plugins.connect(f, HighlightLines(lines, names, css)) mpld3.display() #mpld3.save_html(f, figname + '.html') return mpld3.fig_to_html(f)
def plot_data_mlp_to_html(data_points, labels=[]): # print(len(dataPoints)) data_points = cull_to_number(data_points, 250) # print(len(dataPoints)) # print(dataPoints) swap = swapaxes(data_points, 0, 1) # print(swap) timescale = [] for i, date in enumerate(swap[0]): parsedDate = datetime.datetime.strptime(date, '%m/%d/%y %H:%M:%S') timescale.append(parsedDate) # timescale = [datetime.datetime.strptime(date, '%m/%d/%y %H:%M:%S') for date in swap[0]] dates = matplotlib.dates.date2num(timescale) fig, ax = plt.subplots(figsize=[9.28, 4.8]) plt.rcParams.update({'figure.autolayout': True}) ax.yaxis.set_major_locator(matplotlib.ticker.MultipleLocator(10)) ax.grid(which='major', axis='both', linestyle="-", alpha=0.25, linewidth=1) ax.tick_params(labelsize='medium', width=1) # Read labels from list p1 = ax.plot_date(dates, swap[1], color='red', linestyle='solid', marker=None, label=labels[0]) p2 = ax.plot_date(dates, swap[2], color='green', linestyle='solid', marker=None, label=labels[1]) p3 = ax.plot_date(dates, swap[3], color='blue', linestyle='solid', marker=None, label=labels[2]) s1 = ax.scatter(dates, swap[1], color='#00000000', s=50) s2 = ax.scatter(dates, swap[2], color='#00000000', s=50) s3 = ax.scatter(dates, swap[3], color='#00000000', s=50) ax.legend() # xlabels = ax.get_xticklabels() # plt.setp(xlabels, rotation=30, horizontalalignment='right') ax.set(ylim=[0, 100], xlabel='Dată', ylabel='Procent (%)', title='Grafic umiditate plante') # Create HTML plugins.clear(fig) tooltip_plugin1 = plugins.PointLabelTooltip( s1, extract_point_position(swap[0], swap[1])) tooltip_plugin2 = plugins.PointLabelTooltip( s2, extract_point_position(swap[0], swap[2])) tooltip_plugin3 = plugins.PointLabelTooltip( s3, extract_point_position(swap[0], swap[3])) plugins.connect(fig, tooltip_plugin1, tooltip_plugin2, tooltip_plugin3, plugins.Zoom(), plugins.Reset()) html_str = fig_to_html(fig) return html_str
def test(): fig, ax = plt.subplots(2) # scatter periods and amplitudes np.random.seed(0) P = 0.2 + np.random.random(size=20) A = np.random.random(size=20) x = np.linspace(0, 10, 100) data = np.array([[x, Ai * np.sin(x / Pi)] for (Ai, Pi) in zip(A, P)]) points = ax[1].scatter(P, A, c=P + A, s=200, alpha=0.5) ax[1].set_xlabel('Period') ax[1].set_ylabel('Amplitude') # create the line object # print(type(x)) lines = ax[0].plot(x, 0 * x, '-w', lw=3, alpha=0.5) ax[0].set_ylim(-1, 1) ax[0].set_title("Hover over points to see lines") # transpose line data and add plugin # print(data.shape) linedata = data.transpose(0, 2, 1) print(linedata.shape) # linedata = linedata.tolist() # print(len(linedata[0])) print(type(lines[0]), lines[0]) plugins.connect(fig, LinkedView(points, lines[0], linedata)) mpld3.show()
def testActiveLegend(self): import mpld3 from mpld3 import plugins from mpld3.utils import get_id import numpy as np import collections import matplotlib.pyplot as plt N_paths = 5 N_steps = 100 x = np.linspace(0, 10, 100) y = 0.1 * (np.random.random((N_paths, N_steps)) - 0.5) y = y.cumsum(1) fig = plt.figure(figsize=(16, 7)) # 8 inches wide by 6 inches tall ax = fig.add_subplot(2, 2, 1) # fig, ax = plt.subplots() labels = ["a", "b", "c", "d", "e"] line_collections = ax.plot(x, y.T, lw=4, alpha=0.2) interactive_legend = plugins.InteractiveLegendPlugin( line_collections, labels) plugins.connect(fig, interactive_legend) mpld3.show()
def plot_page_mpld3(df, columns, request): if request.method == 'POST': # Something is being submitted x1 = str(request.form['x1']) x2 = str(request.form['x2']) y1 = str(request.form['y1']) y2 = str(request.form['y2']) z = str(request.form['z']) for requested_col in {x1, x2, y1, y2, z}: if requested_col not in columns: return redirect(url_for('mpld3_plot')) else: x1, x2, y1, y2, z = 'teff', 'vt', 'Vabs', 'feh', 'logg' # Does not work with NaN values! df = df.loc[:, {x1, x2, y1, y2, z}].dropna(axis=0) fig, ax = plt.subplots(2, 2, figsize=(14, 8), sharex='col', sharey='row') points = ax[0, 0].scatter(df[x1], df[y1], c=df[z], alpha=0.6) points = ax[1, 0].scatter(df[x1], df[y2], c=df[z], alpha=0.6) points = ax[0, 1].scatter(df[x2], df[y1], c=df[z], alpha=0.6) points = ax[1, 1].scatter(df[x2], df[y2], c=df[z], alpha=0.6) ax[1, 0].set_xlabel(x1) ax[1, 1].set_xlabel(x2) ax[0, 0].set_ylabel(y1) ax[1, 0].set_ylabel(y2) plugins.connect(fig, plugins.LinkedBrush(points)) plot = fig_to_html(fig) return render_template('plot_mpld3.html', plot=plot, columns=columns, x1=x1, x2=x2, y1=y1, y2=y2, z=z)
def comp_outcome(outcome): fig, ax = plt.subplots() fig.set_size_inches(8, 6) labels_new = [] if outcome == "WON": points = ax.plot(winner_list, 'or', alpha=1,markersize=12, markeredgewidth=1, color = 'red') for i in range(len(df)): if df.iloc[i]["Outcome of Bid"] == "Won Tender Bid": label = df.iloc[[i], :].T label.columns = ['Project {0}'.format(i)] labels_new.append(str(label.to_html())) elif outcome == "LOST": points = ax.plot(losing_list, 'or', alpha=1,markersize=12, markeredgewidth=1, color = 'black') for i in range(len(df)): if df.iloc[i]["Outcome of Bid"] == "Lost Tender Bid": label = df.iloc[[i], :].T label.columns = ['Project {0}'.format(i)] labels_new.append(str(label.to_html())) elif outcome == 'ALL': points = ax.plot(y, 'or', alpha=0.7,markersize=12, markeredgewidth=1, color = 'orange') labels_new = labels tooltip = plugins.PointHTMLTooltip(points[0], labels_new, voffset=10, hoffset=10, css=css) plugins.connect(fig, tooltip) plugins.connect(fig, DragPlugin(points[0])) json01 = json.dumps(mpld3.fig_to_dict(fig)) return(json01)
def plot(self, data, notebook=False, show=True, savename=None): fig = pyplot.figure() ncenters = len(self.centers) colorizer = Colorize() colorizer.get = lambda x: self.colors[int(self.predict(x)[0])] # plot time series of each center # TODO move into a time series plotting function in viz.plots for i, center in enumerate(self.centers): ax = pyplot.subplot2grid((ncenters, 3), (i, 0)) ax.plot(center, color=self.colors[i], linewidth=5) fig.add_axes(ax) # make a scatter plot of the data ax2 = pyplot.subplot2grid((ncenters, 3), (0, 1), rowspan=ncenters, colspan=2) ax2, h2 = scatter(data, colormap=colorizer, ax=ax2) fig.add_axes(ax2) plugins.connect(fig, HiddenAxes()) if show and notebook is False: mpld3.show() if savename is not None: mpld3.save_html(fig, savename) elif show is False: return mpld3.fig_to_html(fig)
def __call__(self, plot, view): if not self._applies(plot, view): return fig = plot.handles['fig'] if 'legend' in plot.handles: plot.handles['legend'].set_visible(False) line_segments, labels = [], [] keys = view.keys() for idx, subplot in enumerate(plot.subplots.values()): if isinstance(subplot, PointPlot): line_segments.append(subplot.handles['paths']) if isinstance(view, NdOverlay): labels.append(str(keys[idx])) else: labels.append(subplot.map.last.label) elif isinstance(subplot, CurvePlot): line_segments.append(subplot.handles['line_segment']) if isinstance(view, NdOverlay): labels.append(str(keys[idx])) else: labels.append(subplot.map.last.label) tooltip = plugins.InteractiveLegendPlugin(line_segments, labels, alpha_sel=self.alpha_sel, alpha_unsel=self.alpha_unsel) plugins.connect(fig, tooltip)
def generate_embedding(param_file, model_file, mnist_file, output_file=None, param_key=None): predictor = optimus.load(model_file) params = biggie.Stash(param_file) param_key = sorted(params.keys())[-1] if param_key is None else param_key predictor.param_values = params.get(param_key) train, valid, test = datatools.load_mnist_npz(mnist_file) idx = np.random.permutation(len(valid[0]))[:2000] x_in = valid[0][idx] y_true = valid[1][idx] z_out = predictor(x_in=x_in)['z_out'] imgfiles = [datatools.generate_imagename(i, y) for i, y in enumerate(idx, y_true)] labels = ['<img src="{}{}" width=100 height=100>'.format(URL_BASE, img) for img in imgfiles] palette = seaborn.color_palette("Set3", 10) colors = np.asarray([palette[y] for y in y_true]) fig = plt.figure(figsize=(10, 10)) ax = fig.gca() handle = ax.scatter(z_out.T[0], z_out.T[1], c=colors, s=75, alpha=0.66) tooltip = plugins.PointHTMLTooltip( handle, labels, voffset=10, hoffset=10) plugins.connect(fig, tooltip) plt.show() if output_file: with open(output_file, 'w') as fp: mpld3.save_html(fig, fp)
def main(): fig, ax = plt.subplots() N = 50 df = pd.DataFrame(index=range(N)) df['x'] = np.random.randn(N) df['y'] = np.random.randn(N) df['z'] = np.random.randn(N) labels = [] for i in range(N): label = df.ix[[i], :].T label.columns = ['Row {0}'.format(i)] labels.append(str(label.to_html())) # .to_html() is unicode, so make leading 'u' go away with str() points = ax.plot(df.x, df.y, 'o', color='k', mec='w', ms=15, mew=1, alpha=.9) ax.set_xlabel('x') ax.set_ylabel('y') tooltip = plugins.PointHTMLTooltip( points[0], labels, voffset=10, hoffset=10, css=css) plugins.connect(fig, tooltip) return fig
def plot(self, notebook=False, colormap='polar', scale=1, maptype='points', show=True, savename=None): # make a spatial map based on the scores fig = pyplot.figure(figsize=(12, 5)) ax1 = pyplot.subplot2grid((2, 3), (0, 1), colspan=2, rowspan=2) if maptype is 'points': ax1, h1 = pointmap(self.scores, colormap=colormap, scale=scale, ax=ax1) elif maptype is 'image': ax1, h1 = imagemap(self.scores, colormap=colormap, scale=scale, ax=ax1) fig.add_axes(ax1) # make a scatter plot of sampled scores ax2 = pyplot.subplot2grid((2, 3), (1, 0)) ax2, h2, samples = scatter(self.scores, colormap=colormap, scale=scale, thresh=0.01, nsamples=1000, ax=ax2, store=True) fig.add_axes(ax2) # make the line plot of reconstructions from principal components for the same samples ax3 = pyplot.subplot2grid((2, 3), (0, 0)) ax3, h3, linedata = tsrecon(self.comps, samples, ax=ax3) plugins.connect(fig, LinkedView(h2, h3[0], linedata)) plugins.connect(fig, HiddenAxes()) if show and notebook is False: mpld3.show() if savename is not None: mpld3.save_html(fig, savename) elif show is False: return mpld3.fig_to_html(fig)
def main(): fig, ax = plt.subplots(2) # scatter periods and amplitudes np.random.seed(0) P = 0.2 + np.random.random(size=20) A = np.random.random(size=20) x = np.linspace(0, 10, 100) data = np.array([[x, Ai * np.sin(x / Pi)] for (Ai, Pi) in zip(A, P)]) points = ax[1].scatter(P, A, c=P + A, s=200, alpha=0.5) ax[1].set_xlabel('Period') ax[1].set_ylabel('Amplitude') # create the line object lines = ax[0].plot(x, 0 * x, '-w', lw=3, alpha=0.5) ax[0].set_ylim(-1, 1) ax[0].set_title("Hover over points to see lines") # transpose line data and add plugin linedata = data.transpose(0, 2, 1).tolist() plugins.connect(fig, LinkedView(points, lines[0], linedata)) return fig
def year_dist(final_year_dict): df = pd.DataFrame(final_year_dict, columns = ['no_studies', 'year']) pos = list(range(len(df['no_studies']))) width = 0.25 fig, ax = plt.subplots( figsize=(23,12)) # Create a bar with riboseq files data in position pos, plt.bar(pos,df['no_studies'], width, alpha=1,color=redhex,linewidth=0,label="Number of studies")#df['readlengths'][0]) # Set the y axis label ax.set_ylabel('Number of studies', labelpad=100,fontsize="21") ax.set_xlabel('Publication year',fontsize="21") # Set the chart's title ax.set_title("No. of studies per year",y=1.05,fontsize="25") # Set the position of the x ticks ax.set_xticks([p + 1 * width for p in pos]) # Set the labels for the x ticks ax.set_xticklabels(df['year']) # Setting the x-axis and y-axis limits plt.xlim(min(pos)-width, max(pos)+width*4) plt.ylim([0, max(df['no_studies'])*1.1]) ax.set_axis_bgcolor(background_col) ax.tick_params('both', labelsize=16) plt.grid(color="white", linewidth=2,linestyle="solid") plugins.connect(fig, plugins.TopToolbar(xoffset=-13, yoffset=115),plugins.DownloadPNG(returnstr="Study distribution by year")) return mpld3.fig_to_html(fig)
def create_plot(self, x, y1, y2): fig, ax = plt.subplots() y1, y1_b, y1_e = trim_list(y1) y2, y2_b, y2_e = trim_list(y2) x_dates = map(string2date, x) ax.set_xlim(left=min((x_dates[y1_b:-y1_e][0], x_dates[y2_b:-y2_e][0])), right=max( (x_dates[y1_b:-y1_e][-1], x_dates[y2_b:-y2_e][-1]))) co = list() co.append(ax.plot(x_dates[y1_b:-y1_e], y1, 'b', label='One')) co.append(ax.plot(x_dates[y2_b:-y2_e], y2, 'r', label='Two')) handles, labels = ax.get_legend_handles_labels( ) # return lines and labels interactive_legend = plugins.InteractiveLegendPlugin( zip(handles, co), labels, alpha_unsel=0.5, alpha_over=1.5, start_visible=True) plugins.connect(fig, interactive_legend) ax.fill_between(x_dates[y1_b:-y1_e], y1, facecolors='blue', alpha=0.5) ax.fill_between(x_dates[y2_b:-y2_e], y2, facecolors='red', alpha=0.5) ax.set_title(self.title) plt.subplots_adjust(right=.8) fig.set_size_inches(10, 8, forward=True) return mpld3.fig_to_html(fig)
def plot(request, title): fig = plt.figure(figsize=(4,4)) ax = plt.gca() if title == None: x = np.linspace(-2, 2, 20) y = x[:, None] X = np.zeros((20, 20, 4)) X[:, :, 0] = np.exp(- (x - 1) ** 2 - (y) ** 2) X[:, :, 1] = np.exp(- (x + 0.71) ** 2 - (y - 0.71) ** 2) X[:, :, 2] = np.exp(- (x + 0.71) ** 2 - (y + 0.71) ** 2) X[:, :, 3] = np.exp(-0.25 * (x ** 2 + y ** 2)) im = ax.imshow(X, extent=(10, 20, 10, 20), origin='lower', zorder=1, interpolation='nearest') fig.colorbar(im, ax=ax) ax.set_title('An Image', size=20) plugins.connect(fig, plugins.MousePosition(fontsize=14)) plot_string = mpld3.fig_to_html(fig, d3_url=None, mpld3_url=None, no_extras=False, template_type='general', figid=None, use_http=False) return HttpResponse(plot_string, status=200) else: plot_string = r.get('user_' + str(0) + '_plot_' + title) return HttpResponse(plot_string, status=200)
def plot_xy_bootstrapped(xs, ys, thresholds, xlabel, ylabel, labels=False, labels_left=False, ax=None, fig=None, label=None, **plot_kwargs): if ax is None or fig is None: fig1, ax1 = plt.subplots() if fig is None: fig = fig1 if ax is None: ax = ax1 for i in range(1, len(xs)): ax.plot(xs[i], ys[i], '-', alpha=0.3) (xs_, ys_, thresholds_) = make_points_far(xs[0], ys[0], thresholds) label_text = ["Threshold: %s (%s, %s)" % (t, pretty_point(x), pretty_point(y)) for (x, y, t) in zip(xs_, ys_, thresholds_)] if label is None: scatter = ax.plot(xs_, ys_, '-o', **plot_kwargs) plugins.connect(fig, plugins.PointHTMLTooltip(scatter[0], label_text)) else: scatter = ax.plot(xs_, ys_, '-o', label=label, **plot_kwargs) plugins.connect(fig, plugins.PointHTMLTooltip(scatter[0], label_text)) if labels: draw_labels(ax, xs_, ys_, thresholds_, labels_left=labels_left) plt.xlim(0, 1) plt.ylim(0, 1) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.tight_layout() if label is not None: handles, labels = ax.get_legend_handles_labels() ax.legend(handles[::-1], labels[::-1], loc='best') return save_image()
def tracking(animal_id, session, scan_idx): form = TrackingForm(request.form) key = dict( animal_id=animal_id, session=session, scan_idx=scan_idx, ) figure = None if pupil.Eye() & key: prev = (pupil.Eye() & key).fetch1('preview_frames') fig, ax = plt.subplots(4,4,figsize=(10, 8), sharex="col", sharey="row") for a, fr in zip(ax.ravel(), prev.transpose([2,0,1])): a.imshow(fr, cmap='gray', interpolation='bicubic') a.axis('off') a.set_aspect(1) plugins.connect(fig, plugins.LinkedBrush([])) # TODO Edgar change that here figure = mpld3.fig_to_html(fig) else: flash('Could not find figure for key {}'.format(str(key))) if request.method == 'POST' and form.validate(): pass return render_template('trackingtask.html', form=form, figure=figure)
def __call__(self, plot, view): if not self._applies(plot, view): return fig = plot.handles['fig'] if 'legend' in plot.handles: plot.handles['legend'].set_visible(False) line_segments, labels = [], [] keys = view.keys() for idx, subplot in enumerate(plot.subplots.values()): if isinstance(subplot, PointPlot): line_segments.append(subplot.handles['paths']) if isinstance(view, NdOverlay): labels.append(str(keys[idx])) else: labels.append(subplot.hmap.last.label) elif isinstance(subplot, CurvePlot): line_segments.append(subplot.handles['line_segment']) if isinstance(view, NdOverlay): labels.append(str(keys[idx])) else: labels.append(subplot.hmap.last.label) tooltip = plugins.InteractiveLegendPlugin(line_segments, labels, alpha_sel=self.alpha_sel, alpha_unsel=self.alpha_unsel) plugins.connect(fig, tooltip)
def get_plot(date=None, output='html'): date = date or dt.datetime.now() fig, ax = plt.subplots(figsize=(10, 4)) plot_db_data(ax, date) plot_forecast(ax, date) plot_grid(fig, ax) handles, labels = ax.get_legend_handles_labels() if output == 'html': interactive_legend = plugins.InteractiveLegendPlugin(handles, labels) plugins.connect(fig, interactive_legend) fig.subplots_adjust(right=0.7) plot_html = mpld3.fig_to_html(fig, template_type='general') return plot_html else: ax.legend(handles, labels) plt.savefig('./static/graph/graph.png') plt.close() f = open('./static/graph/graph.png', 'rb') return f
def plot_topics_mpld3(H, tweet_dict): ''' INPUT - H topic matrix from NMF - tweet_dict - dictionary of tweet information which includes: the most important tweet the percent of tweets that fall into a certain topic the sentence important of each tweet under each topic the top words OUTPUT - creates a plot using mpl3d Returns nothing ''' pca = PCA(n_components=2) hflat = pca.fit_transform(H) xs, ys = hflat[:, 0], hflat[:, 1] topic_size = tweet_dict['topic_size_pct'] cluster_names = tweet_dict['top_words'] titles = tweet_dict['exemplary_tweet'] clusdf = pd.DataFrame(dict(x=xs, y=ys, label=range(hflat.shape[0]))) clusdf['title'] = clusdf['label'].apply(lambda label: titles[label]) fig, ax = plt.subplots(figsize=(17, 9)) ax.margins(0.03) box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * .8, box.height]) for name, x, y in zip(clusdf.label.values, clusdf.x.values, clusdf.y.values): points = ax.plot(x, y, marker='o', linestyle='', ms=topic_size[name], label=cluster_names[name]) ax.set_aspect('auto') ax.axes.get_xaxis().set_ticks([]) ax.axes.get_yaxis().set_ticks([]) ax.axes.get_xaxis().set_visible(False) ax.axes.get_yaxis().set_visible(False) tooltip = \ plugins.PointLabelTooltip(points[0], labels=[clusdf.title.values[name]]) plugins.connect(fig, tooltip) ax.set_xlabel('PC 1') ax.set_ylabel('PC 2') # for i in range(len(clusdf)): # ax.text(clusdf.ix[i]['x'], clusdf.ix[i]['y'], # clusdf.ix[i]['title'], size=12) lgnd = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), numpoints=1, title='Top Words Used in the Topics', frameon=False, markerscale=1) for i in range(H.shape[0]): lgnd.legendHandles[i]._legmarker.set_markersize(12) lgnd.legendHandles[i]._legmarker.set_markersize(12) # plt.show() mpld3.show()
def scatter_interactive(fig, scatter_plot, df, file_name, figsize=False): from jinja2 import Environment, FileSystemLoader from mpld3 import plugins from helpers.application_helper import PointClickableHTMLTooltip2 # file_path = './assets/interactive_plots/'+file_name file_path = file_name env = Environment(loader=FileSystemLoader('./views')) restaurants = df.to_dict(orient='records') restaurant_template = env.get_template('restaurant.jinja') cards = [ restaurant_template.render(restaurant=restaurant) for restaurant in restaurants ] if figsize: fig.set_size_inches(figsize) else: fig.set_size_inches(8.5, 8.5) plugins.connect( fig, PointClickableHTMLTooltip2(scatter_plot, labels=cards, targets=df['url'].tolist(), css=load_css(raw=True))) mpld3.save_html(fig, file_path) button = '''<a class='btn btn-default' style="text-decoration: none;;" href="{0}" target='_blank'> Interactive Scatter Plot</a> '''.format(file_path) return HTML(button)
def doRenderChart(self, handlerId, dialogTemplate, dialogOptions, aggregation, keyFields, keyFieldValues, keyFieldLabels, valueFields, valueFieldValues): # go fig, ax = plt.subplots(figsize=(6, 4)) dialogBody = self.renderTemplate(dialogTemplate, **dialogOptions) if (len(keyFieldLabels) > 0 and self.supportsKeyFieldLabels(handlerId) and self.supportsAggregation(handlerId)): plugins.connect(fig, ChartPlugin(self, keyFieldLabels)) plugins.connect(fig, DialogPlugin(self, handlerId, dialogBody)) colormap = cm.jet self.doRenderMpld3(handlerId, fig, ax, colormap, keyFields, keyFieldValues, keyFieldLabels, valueFields, valueFieldValues) self.setChartSize(handlerId, fig, ax, colormap, keyFields, keyFieldValues, keyFieldLabels, valueFields, valueFieldValues) self.setChartGrid(handlerId, fig, ax, colormap, keyFields, keyFieldValues, keyFieldLabels, valueFields, valueFieldValues) self.setChartLegend(handlerId, fig, ax, colormap, keyFields, keyFieldValues, keyFieldLabels, valueFields, valueFieldValues) self.setChartTitle(handlerId) #Render the figure self.renderFigure(fig, dialogBody)
def mpld3(self, conjunto: pd.DataFrame): plot_dims = (20, 10) fig, ax = plt.subplots(figsize=plot_dims) ax.grid(True, alpha=0.3) labels = conjunto['county'].tolist() points = ax.plot(conjunto.cases, conjunto.deaths, 'o', color='b', mec='k', ms=15, mew=1, alpha=.6) ax.set_xlabel('Casos de COVID-19') ax.set_ylabel('Mortes por COVID-19') ax.set_title( 'Relação entre casos e mortes nos condados americanos por COVID-19', size=20) tooltip = plugins.PointHTMLTooltip(points[0], labels, voffset=10, hoffset=10) plugins.connect(fig, tooltip) # mpld3.display() # mpld3.show() return mpld3
def __call__(self, plot, view): if not self._applies(plot, view): return fig = plot.handles['fig'] labels = [self.format_string.format(label=view.label)] tooltip = plugins.LineHTMLTooltip(plot.handles['line_segment'], labels, voffset=self.voffset, hoffset=self.hoffset, css=self.css) plugins.connect(fig, tooltip)
def create_plot(): fig, ax = plt.subplots() points = ax.scatter(np.random.rand(50), np.random.rand(50), s=500, alpha=0.3) plugins.clear(fig) plugins.connect(fig, plugins.Reset(), plugins.Zoom(), ClickInfo(points)) return fig
def after(self): if self.draw: plugins.connect( self.fig, plugins.InteractiveLegendPlugin( self.s1, self.labels, ax=self.ax)) mpld3.show() else: pass
def after(self): if self.draw: plugins.connect( self.fig, plugins.InteractiveLegendPlugin( self.s1, self.labels, ax=self.ax)) mpld3.display() else: print meeting.minutes
def plot_ts(*args, **kwargs): """ Create an interactive JavaScript T-S plot. """ ax = nplt.plot_ts(*args, **kwargs) pg = InteractiveLegendPlugin(ax.lines, kwargs.get("labels", [lin.get_label() for lin in ax.lines]), alpha_unsel=kwargs.get("alpha", 0.2)) plugins.connect(ax.figure, pg) mpld3.display() return ax
def doRenderChart(self): self.colormap = cm.jet # set defaults for plot plt.rcParams['savefig.dpi'] = 96 plt.rcParams['font.family'] = "serif" plt.rcParams['font.serif'] = "cm" fig = None try: # go fig, ax = self.createFigure() if self.useMpld3: #TODO: rework this piece #keyFieldLabels = self.getKeyFieldLabels() #if (len(keyFieldLabels) > 0 and self.supportsKeyFieldLabels(self.handlerId) and self.supportsAggregation(self.handlerId)): # plugins.connect(fig, ChartPlugin(self, keyFieldLabels)) plugins.connect(fig, DialogPlugin(self, self.handlerId, self.dialogBody)) #let subclass do the actual rendering newAx = self.matplotlibRender(fig, ax) if newAx is not None: ax = newAx axes = ax if not isinstance(axes, (list,np.ndarray)): axes = np.asarray([axes]) #finalize the chart for i, a in np.ndenumerate(axes): if a.title is None or not a.title.get_visible() or a.title.get_text() == '': self.setLegend(fig, a) self.setTicks(fig, a) sharex = True if len(axes) <=1 else len([a for a in axes if a._sharex is not None]) > 0 if len(axes)>1 and not sharex: #adjust the height between subplots plt.subplots_adjust(hspace=self.getSubplotHSpace()) #mpld3 has a bug when autolocator are used. Change to FixedLocators if self.useMpld3: self.addMessage("Warning: While great, D3 rendering is using MPLD3 library which has limitations that have not yet been fixed") from matplotlib import ticker self.debug("Converting to FixedLocator for mpld3") for a in axes: locator = a.xaxis.get_major_locator() if not isinstance(locator, ticker.FixedLocator): vmin,vmax = a.xaxis.get_data_interval() a.xaxis.set_major_locator(ticker.FixedLocator(locator.tick_values(vmin, vmax))) #Render the figure return self.renderFigure(fig) finally: if fig is not None: plt.close(fig)
def main(): fig, ax = plt.subplots() xx = np.arange(12) yy = [3,1,4,1,5,9,2,6,5,3,5,9] ax.plot(xx, yy, 'ks-', ms=10, mec='w', mew=3) ax.set_title('Reset Button Test', size=14) plugins.connect(fig, plugins.ResetButton()) return fig
def main(): fig, ax = plt.subplots(2, 2, sharex='col', sharey='row') X = np.random.normal(0, 1, (2, 100)) for i in range(2): for j in range(2): points = ax[1 - i, j].scatter(X[i], X[j]) plugins.connect(fig, plugins.LinkedBrush(points)) return fig
def main(): fig, ax = plt.subplots() colors = plt.rcParams['axes.color_cycle'] points = [] for i, color in enumerate(colors): points = ax.plot(i, 0, 'o', c=color) plugins.connect(fig, plugins.PointLabelTooltip(points[0], [color])) ax.set_xlim(-1, len(colors) + 1) return fig
def __call__(self, plot, view): if not self._applies(plot, view): return fig = plot.handles["fig"] for i, (key, bar) in enumerate(plot.handles["bars"].items()): handle = bar.get_children()[0] selection = [(d.name, {k}) for d, k in zip(plot.bar_dimensions, key) if d is not None] label_data = view.select(**dict(selection)).dframe().ix[0].to_frame() label = str(label_data.to_html(header=len(view.label) > 0)) tooltip = plugins.LineHTMLTooltip(handle, label, voffset=self.voffset, hoffset=self.hoffset, css=self.css) plugins.connect(fig, tooltip)
def main(file_name='Greenland1km.nc'): '''Description''' # Set up the file and projection data = os.path.dirname(os.path.abspath(__file__)) + os.sep + '..' + os.sep \ + 'data' + os.sep + file_name proj_file = pyproj.Proj('+proj=stere +ellps=WGS84 +datum=WGS84 +lat_ts=71.0 +lat_0=90 ' \ + '+lon_0=321.0 +k_0=1.0') proj_lat_long = pyproj.Proj('+proj=latlong +ellps=WGS84 +datum=WGS84') fig, ax = plt.subplots(1,2) # Open up the file and grab the data we want out of it greenland = Dataset(data) x = greenland.variables['x'][:] y = greenland.variables['y'][:] nx = x.shape[0] ny = y.shape[0] y_grid, x_grid = scipy.meshgrid(y[:], x[:], indexing='ij') thk = greenland.variables['thk'][0] bheatflx = greenland.variables['bheatflx'][0] # Now transform the coordinates to the correct lats and lons lon, lat = pyproj.transform(proj_file, proj_lat_long, x_grid.flatten(), y_grid.flatten()) lat = lat.reshape(ny,nx) lon = lon.reshape(ny,nx) # Put thickness in a basemap mapThk = Basemap(projection='stere',lat_0=65, lon_0=-25,\ llcrnrlat=55,urcrnrlat=85,\ llcrnrlon=-50,urcrnrlon=0,\ rsphere=6371200.,resolution='l',area_thresh=10000, ax=ax[0]) mapThk.drawcoastlines(linewidth=0.25) mapThk.fillcontinents(color='grey') mapThk.drawmeridians(np.arange(0,360,30)) mapThk.drawparallels(np.arange(-90,90,30)) x, y = mapThk(lon,lat) cs = mapThk.contour(x, y, thk, 3) # Put basal heat flux in a basemap mapFlx = Basemap(projection='stere',lat_0=65, lon_0=-25,\ llcrnrlat=55,urcrnrlat=85,\ llcrnrlon=-50,urcrnrlon=0,\ rsphere=6371200.,resolution='l',area_thresh=10000, ax=ax[1]) mapFlx.drawcoastlines(linewidth=0.25) mapFlx.fillcontinents(color='grey') mapFlx.drawmeridians(np.arange(0,360,30)) mapFlx.drawparallels(np.arange(-90,90,30)) x, y = mapFlx(lon,lat) cs = mapFlx.contour(x, y, bheatflx, 3) plugins.connect(fig, ClickInfo(cs)) mpld3.show()
def PlotNetwork(G): N = len(G.nodes()) pos = nx.spring_layout(G) # Adding attributes to nodes for node in G.nodes(): G.node[node]['pos'] = pos[node] # Creating color palette: # Calculating maximum degree in the graph: maxDegree = G.degree()[max(G.degree(), key=G.degree().get)] # Need to simplify hexCodes = utils.get_N_HexCol(maxDegree + 1) nodesColor = ["#" + hexCodes[G.degree()[node]] for node in G.nodes()] nodesDegree = [G.degree()[i] for i in G.nodes()] nodesCluster = [nx.clustering(G)[i] for i in G.nodes()] df = pd.DataFrame(index=range(N)) df['Degree'] = nodesDegree df['Cluster'] = nodesCluster labels = [] for i in range(N): label = df.ix[[i], :].T label.columns = ['Row {0}'.format(i)] labels.append(str(label.to_html())) # Creating canvas fig, ax = plt.subplots() for edge in G.edges(): x0, y0 = G.node[edge[0]]['pos'] # Beginning of an edge point x1, y1 = G.node[edge[1]]['pos'] # End of an edge point ax.plot([x0,x1],[y0,y1], color='grey', lw=1.5, alpha=0.5) points = ax.scatter([(G.node[node]['pos'])[0] for node in G.nodes()], [(G.node[node]['pos'])[1] for node in G.nodes()], c=nodesColor, s = 220, alpha=1, lw = 3) tooltip = plugins.PointHTMLTooltip(points, labels, voffset=10, hoffset=10, css=utils.CSSTableStyle()) plugins.connect(fig, tooltip) #mpld3.show() #mpld3.save_html(fig, "Plot_" + str(30-len(G.nodes())) + ".html") #plt.close(fig) return mpld3.fig_to_html(fig)
def main(): N_paths = 50 N_steps = 100 x = np.linspace(0, 10, 100) y = 0.1 * (np.random.random((N_paths, N_steps)) - 0.5) y = y.cumsum(1) fig, ax = plt.subplots(subplot_kw={'xticks': [], 'yticks': []}) lines = ax.plot(x, y.T, color='blue', lw=4, alpha=0.1) plugins.connect(fig, HighlightLines(lines)) return mpld3.fig_to_html(fig, template_type='simple')
def __call__(self, plot, view): if not self._applies(plot, view): return fig = plot.handles['fig'] df = view.dframe() labels = [] for i in range(len(df)): label = df.ix[[i], :].T label.columns = [view.label] labels.append(str(label.to_html(header=len(view.label)>0))) tooltip = plugins.PointHTMLTooltip(plot.handles['paths'], labels, voffset=self.voffset, hoffset=self.hoffset, css=self.css) plugins.connect(fig, tooltip)
def plot_lasso_path(df, resp_var, exp_vars): """ Plot the lasso path. Both response and explanatory variables are standardised first. Args: df: Dataframe resp_var: String. Response variable exp_vars: List of strings. Explanatory variables Returns: Dataframe of path and matplotlib figure with tooltip- labelled lines. To view this figure in a notebook, use mpld3.display(f) on the returned figure object, f. """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import mpld3 from mpld3 import plugins from sklearn.preprocessing import StandardScaler from sklearn.linear_model import lasso_path # Standardise the feature data and response feat_std = StandardScaler().fit_transform(df[[resp_var,] + exp_vars]) # Calculate lasso path alphas, coefs, _ = lasso_path(feat_std[:, 1:], # X feat_std[:, 0], # y eps=1e-3, # Path length fit_intercept=False) # Already centred # -Log(alphas) is easier for display neg_log_alphas = -np.log10(alphas) # Build df of results res_df = pd.DataFrame(data=coefs.T, index=alphas, columns=exp_vars) # Plot fig, ax = plt.subplots() for coef, name in zip(coefs, exp_vars): line = ax.plot(neg_log_alphas, coef, label=name) plugins.connect(fig, plugins.LineLabelTooltip(line[0], label=name)) plt.xlabel('-Log(alpha)') plt.ylabel('Coefficients') plt.title('Lasso paths') plt.legend(loc='best', title='', ncol=3) return res_df, fig
def create_plot(): fig, ax = plt.subplots(2, 2, sharex='col', sharey='row') fig.subplots_adjust(hspace=0.3) for i in range(2): for j in range(2): txt = '({i}, {j})'.format(i=i, j=j) ax[i, j].set_title(txt, size=14) ax[i, j].text(0.5, 0.5, txt, size=40, ha='center') ax[i, j].grid(True, color='lightgray') ax[i, j].set_xlabel('xlabel') ax[i, j].set_ylabel('ylabel') plugins.connect(fig, plugins.MousePosition()) return fig
def __call__(self, plot, view): if not self._applies(plot, view): return fig = plot.handles['fig'] df = view.dframe() labels = [] for i in range(len(df)): label = df.ix[[i], :].T label.columns = [view.label] labels.append(str(label.to_html(header=len(view.label)>0))) for i, (bar, label) in enumerate(zip(plot.handles['bars'].get_children(), labels)): tooltip = plugins.LineHTMLTooltip(bar, label, voffset=self.voffset, hoffset=self.hoffset, css=self.css) plugins.connect(fig, tooltip)
def plot_comparison(dataset_identifiers, features, type="boxplot"): sns.set_style("whitegrid") sns.set_palette("deep") generator = "matplot" f, axes = plt.subplots(1, 2) # dataset_identifiers = ['DESeq_1_18_0_umc_read_counts_table_without_8433', # 'DESeq_1_18_0_genentech_read_counts_table'] # features = ["ENSG00000002549"] path = APP_CONFIG["application_files_location"] + APP_CONFIG["application_store_name"] i = 0 subset = None print features for d in dataset_identifiers: dataset = dr.get_data_frame_from_hdf(d, path) if type != "pca": subset = dataset.ix[features, :] if type == "boxplot": axes[i].boxplot(subset) create_csv_version(subset.transpose(), d, type, subset.columns) if type == "scatter": generator = "matplot" #print len(subset.ix[0, :]) t = axes[i].plot(subset.transpose(), 'o') create_csv_version(subset.transpose(), d, type, subset.columns) plugins.connect(f, plugins.PointLabelTooltip(t[0], labels=(list(subset.columns)))) if type == "pca": print(type) pca = PCA(n_components=2) t_data = dataset.transpose() pca_result = pca.fit(t_data) pca_transformed = pca_result.transform(t_data) t = axes[i].plot(pca_transformed[:, 0], pca_transformed[:, 1], 'o') create_csv_version(pca_transformed, d, type, dataset.columns) plugins.connect(f, plugins.PointLabelTooltip(t[0], labels=(list(dataset.columns)))) axes[i].set_xlabel(d) axes[i].set_ylabel(str(features)) i += 1 if generator == "bokeh": bk = to_bokeh(name="descriptive") else: bk = plt.gcf() sz = bk.get_size_inches() bk.set_size_inches((sz[0]*2.5, sz[1]*2)) return bk