def live_render_plot_update_example(): fig = get_total_infected_people_figure(["#75968f", "#933b41", "#550b1d"]) js, tag = autoload_static(fig, INLINE, f"{PROTOCOL}://{DOMAIN}:{PORT}/plot.js") return tag, js
def plotbar(events, userid): xvalues = [x1.title for x1 in events] y1values=[y1.prefearfactor for y1 in events] y2values=[y2.postfearfactor for y2 in events] yr=OrderedDict(PredictedFear=y1values, ActualFear=y2values) plotheight=400 plotwidth=600 p2 = figure(x_range=xvalues, plot_width=plotwidth, plot_height=plotheight, title="Imagined vs real") #p2.xaxis.major_label_orientation = "vertical" p2.xaxis.major_label_orientation = pi/4 p2.vbar(x=xvalues, top=y1values, width=0.5, fill_color="red") p2.vbar(x=xvalues, top=y2values, width=0.5, fill_color="blue") userfilepath=filepath+str(userid)+'.js' js, tag = autoload_static(p2, CDN, '/'+userfilepath+'?id='+str(randint(1, 1000000))) with open(userfilepath, 'w') as f: f.write(js) return js,tag
def get_plottag(script_path): """ Saves js in script_path and returns tag for embedding in html """ import numpy as np import pandas as pd import os y_data = np.random.randn(100) x_data = pd.date_range('31-Aug-2014', periods=len(y_data)) figure(x_axis_type='datetime', tools='pan,wheel_zoom,box_zoom,reset,previewsave,crosshair', name='test plot') hold() line(x_data, y_data, line_color="#D95B43", line_width=4, alpha=0.7, legend='random', background_fill= '#cccccc') circle(x_data, y_data, color='red', fill_color=None, size=6, legend='random') curplot().title = 'Test Plot' xaxis().axis_label='date' yaxis().axis_label='some random numbers' grid().grid_line_color='white' grid().grid_line_alpha = 0.5 plotid = curplot()._id script_path = os.path.join(script_path, plotid+'.js') js, tag = autoload_static(curplot(), CDN, script_path=script_path) with open(script_path, 'w') as f: f.write(js) return tag
def _process_script(source, filename, env, js_name, use_relative_paths=False): # Explicitly make sure old extensions are not included until a better # automatic mechanism is available Model._clear_extensions() # quick and dirty way to inject Google API key if "GOOGLE_API_KEY" in source: GOOGLE_API_KEY = getenv('GOOGLE_API_KEY') if GOOGLE_API_KEY is None: if env.config.bokeh_missing_google_api_key_ok: GOOGLE_API_KEY = "MISSING_API_KEY" else: raise SphinxError( "The GOOGLE_API_KEY environment variable is not set. Set GOOGLE_API_KEY to a valid API key, " "or set bokeh_missing_google_api_key_ok=True in conf.py to build anyway (with broken GMaps)" ) run_source = source.replace("GOOGLE_API_KEY", GOOGLE_API_KEY) else: run_source = source c = ExampleHandler(source=run_source, filename=filename) d = Document() c.modify_document(d) if c.error: raise RuntimeError(c.error_detail) resources = get_sphinx_resources() js_path = join(env.bokeh_plot_auxdir, js_name) js, script = autoload_static(d.roots[0], resources, js_name) with open(js_path, "w") as f: f.write(js) return (script, js, js_path, source)
def javascript(self) -> str: """javascript to save""" if self._javascript is None: self._javascript, self._source = autoload_static(self.figure, self.bokeh_source, self.file_name) return self._javascript
def cliffTable_bokeh(cliff): """ Returns a JavaScript tag for embedding a Bokeh DataTable on the website. stats: a Pandas DataFrame conatining AID statistical information """ cliff.insert(0, 'Target CID', cliff.index) source = ColumnDataSource(cliff) columns = [ TableColumn(field="Target CID", title="Target CID"), TableColumn(field="NN_CID", title="NN_CID"), TableColumn(field="Similarity", title="Similarity"), TableColumn(field="Target_Activity", title="Target_Activity"), TableColumn(field="NN_Activity", title="NN_Activity"), TableColumn(field="Cliff", title="Cliff"), ] data_table = DataTable(source=source, columns=columns, editable=False, height=1600, fit_columns=True, row_headers=False) js, tag = autoload_static(data_table, CDN, 'static/js/clifftable.js') js_file = open('static/js/clifftable.js', 'w') js_file.write(js) js_file.close() return tag
def live_render_plot(): fig = get_total_infected_people_figure([ "#75968f", "#a5bab7", "#c9d9d3", "#e2e2e2", "#dfccce", "#ddb7b1", "#cc7878", "#933b41", "#550b1d" ]) js, tag = autoload_static(fig, INLINE, f"{PROTOCOL}://{DOMAIN}:{PORT}/plot.js") return tag, js
def get_slider(): slider = Slider(start=0.1, end=4, value=1, step=.1, title="power") slider.js_on_change( 'value', CustomJS(args=dict(), code=get_slider_callback_function())) js, tag = autoload_static(slider, INLINE, f"{PROTOCOL}://{DOMAIN}:{PORT}/plot.js") return tag, js
def run(self, *args, show=False, **kwargs): # html = file_html(self.fig, CDN, self.div_id) if show: plotting.output_notebook() fig = self.create_fig(*args, **kwargs) if show: bokeh.plotting.show(fig) else: js, tag = autoload_static(fig, CDN, self.js_path) return fig, js, tag
def plotbar(events, userid): """ Arch: I tried to install bokeh 0.10.0 ver and that was giving a lot of errors in the Bar(method args)- StopIteration and also while trying to load the latest bokeh.min.js from CDN So I am going back to the bokeh 0.8.1 ver- at least it works """ xr = [x.title for x in events] y1values = [y1.prefearfactor for y1 in events] y2values = [y2.postfearfactor for y2 in events] yr = OrderedDict(PredictedFear=y1values, ActualFear=y2values) """ height=400 width=600 bar = figure(plot_width=width, plot_height=height, title="Imagined vs real") # use the `rect` renderer to display stacked bars of the medal results. Note # that we set y_range explicitly on the first renderer bar.rect(xr, y1values, height=0.5, width=0.4, color="red", alpha=0.6) bar.rect(xr, y2values, height=0.5, width=0.4, color="blue", alpha=0.6) """ bar = Bar(yr, xr, xlabel="Events", ylabel="Fear factor", title="Imagined vs real fear", width=800, height=600, legend=True, palette=['#c1ff55', '#b7feea'], stacked=True, tools=None, xgrid=None, ygrid=None) bar.toolbar_location = None #output_file("stacked_bar.html", autosave=True) #show(bar) - commented out so it doesnt try to open display in linux #generating unique filenames by- concatenating userid to a rolledindex- #we dont expect a user to generate more than """ global rollingindex userfilepath = filepath+str(userid)+str(rollingindex.next())+'.js' """ userfilepath = filepath + str(userid) + '.js' js, tag = autoload_static( bar, CDN, '/' + userfilepath + '?id=' + str(randint(1, 1000000))) with open(userfilepath, 'w') as f: f.write(js) return js, tag
def changelist_view(self, request, extra_context=None): response = super().changelist_view(request, extra_context=extra_context) if hasattr(response, "context_data"): queryset = response.context_data["cl"].queryset if queryset.exists(): figure = queryset.plot_summary_info() js, tag = autoload_static(figure, CDN, "tmp_bokeh_figure") curdoc().theme = "dark_minimal" extra_context = {"bokeh_tag": tag, "bokeh_js": js} response.context_data.update(extra_context) return response
def embed_fig(p, js_file): js, tag = autoload_static(p, CDN, "/js/" + js_file) with open("js/" + js_file, 'w') as f: f.write(js) reg = '\n<script src="/js/' + js_file + '".*?>.*?</script>' for file in glob("_drafts/*.markdown") + glob("_posts/**/*.markdown"): with open(file, 'r') as f: text = f.read() if re.findall(reg, text): new_text = re.sub(reg, tag, text) with open(file, 'w') as f: f.write(new_text)
def plot(newest_changes): filelist = os.listdir('/home/maximilianklein/snapshot_data/{}/'.format(newest_changes)) site_linkss_file = [f for f in filelist if f.startswith('site_linkss')][0] if newest_changes == 'newest-changes': date_range = site_linkss_file.split('site_linkss-index-from-')[1].split('.csv')[0].replace('-',' ') csv_to_read = '/home/maximilianklein/snapshot_data/{}/{}'.format(newest_changes,site_linkss_file) df = pandas.DataFrame.from_csv(csv_to_read) no_gender_perc = df['nan'].sum() / df.sum().sum() print('no gender %', no_gender_perc) del df['nan'] df['total'] = df.sum(axis=1) df['nonbin'] = df['total'] - df['male'] - df['female'] df['fem_per'] = df['female'] / (df['total']) df['nonbin_per'] = df['nonbin'] / df['total'] dfs = df.sort('total', ascending=False) htmltable = dfs[['total','fem_per','nonbin_per']] htmltable.columns=['Total','Women %', 'Non-binary %'] table_html = htmltable.to_html(na_rep='n/a', max_rows=20) TOOLS = "pan,wheel_zoom,box_zoom,reset,hover,save" title_suffix = 'Changes since {}'.format(date_range) if newest_changes == 'newest-changes' else 'All Time' p = figure(x_axis_type="log", x_range=[0.1, 10**6], y_range=[0, 1], title="Language by Gender {}".format(title_suffix), tools=TOOLS) p.circle(dfs['total'], dfs['fem_per'], size=12, line_color="black", fill_alpha=0.8) p.text(dfs["total"]+0.001, dfs["fem_per"]+0.001, text=dfs.index,text_color="#333333", text_align="center", text_font_size="10pt") hover = p.select(dict(type=HoverTool)) hover.point_policy = "follow_mouse" hover.tooltips = OrderedDict([ ("Language", "@lang_name"), ("Total gendered biographies", "@gendered_total"), ("Percentage Female biographies", "@fem_percent") ]) js_filename = "gender_by_language_{}.js".format(newest_changes) output_path = "./files/assets/js/" script_path = "./assets/js/" # generate javascript plot and corresponding script tag js, tag = autoload_static(p, CDN, script_path + js_filename) with open(output_path + js_filename, 'w') as js_file: js_file.write(js) return {'plot_tag':tag, 'table_html':table_html}
def test_script_attrs(self, mock_make_id): js, tag = embed.autoload_static(_embed_test_plot, CDN, "some/path") html = bs4.BeautifulSoup(tag) scripts = html.findAll(name='script') self.assertEqual(len(scripts), 1) attrs = scripts[0].attrs self.assertTrue(set(attrs), set(['src', 'data-bokeh-model-id', 'id', 'data-bokeh-doc-id'])) self.assertEqual(attrs['data-bokeh-doc-id'], 'ID') self.assertEqual(attrs['data-bokeh-model-id'], str(_embed_test_plot._id)) self.assertEqual(attrs['src'], 'some/path')
def test_script_attrs(self, mock_uuid): mock_uuid.uuid4 = mock.Mock() mock_uuid.uuid4.return_value = "uuid" js, tag = embed.autoload_static(_embed_test_plot, CDN, "some/path") html = bs4.BeautifulSoup(tag) scripts = html.findAll(name="script") self.assertEqual(len(scripts), 1) attrs = scripts[0].attrs self.assertTrue(set(attrs), set(["src", "data-bokeh-model-id", "async", "id", "data-bokeh-doc-id"])) self.assertEqual(attrs["async"], "false") self.assertEqual(attrs["data-bokeh-doc-id"], "uuid") self.assertEqual(attrs["data-bokeh-model-id"], str(_embed_test_plot._id)) self.assertEqual(attrs["src"], "some/path")
def changelist_view(self, request, extra_context=None): response = super().changelist_view(request, extra_context=extra_context) if hasattr(response, "context_data"): queryset = response.context_data["cl"].queryset if queryset.count() > 10: month_distribution_plot = queryset.plot_measurement_by_month() figure_layout = [month_distribution_plot] figure = layout(figure_layout) js, tag = autoload_static(figure, CDN, "tmp_bokeh_figure") extra_context = {"bokeh_tag": tag, "bokeh_js": js} response.context_data.update(extra_context) return response
def test_script_attrs(self, mock_make_id): js, tag = embed.autoload_static(_embed_test_plot, CDN, "some/path") html = bs4.BeautifulSoup(tag) scripts = html.findAll(name='script') self.assertEqual(len(scripts), 1) attrs = scripts[0].attrs self.assertTrue( set(attrs), set(['src', 'data-bokeh-model-id', 'id', 'data-bokeh-doc-id'])) self.assertEqual(attrs['data-bokeh-doc-id'], 'ID') self.assertEqual(attrs['data-bokeh-model-id'], str(_embed_test_plot._id)) self.assertEqual(attrs['src'], 'some/path')
def process_source(self, source, path, js_filename): Model._clear_extensions() root, docstring = _evaluate_source(source, path, self.env) height_hint = root._sphinx_height_hint() js_path = join(self.env.bokeh_plot_auxdir, js_filename) js, script_tag = autoload_static(root, RESOURCES, js_filename) with open(js_path, "w") as f: f.write(js) return (script_tag, js_path, source, docstring, height_hint)
def plot(newest_changes): filelist = os.listdir( '/home/maximilianklein/snapshot_data/{}/'.format(newest_changes)) culture_file = [f for f in filelist if f.startswith('culture')][0] if newest_changes == 'newest-changes': date_range = culture_file.split('culture-index-from-')[1].split( '.csv')[0].replace('-', ' ') print(date_range) csv_to_read = '/home/maximilianklein/snapshot_data/{}/{}'.format( newest_changes, culture_file) df = pandas.DataFrame.from_csv(csv_to_read) no_gender_perc = df['nan'].sum() / df.sum().sum() del df['nan'] df['total'] = df.sum(axis=1) df['nonbin'] = df['total'] - df['male'] - df['female'] df['fem_per'] = df['female'] / (df['total']) df['nonbin_per'] = df['nonbin'] / df['total'] df['fem_per_million'] = df['fem_per'] * 1000000 df['nonbin_per_million'] = df['nonbin_per'] * 1000000 dfs = df.sort('female') interesante = ['female', 'male', 'nonbin'] htmltable = dfs[interesante] htmltable.columns = ['Women', 'Men', 'Non-binary'] table_html = htmltable.to_html(na_rep='n/a') title_suffix = 'Changes since {}'.format( date_range) if newest_changes == 'newest-changes' else 'All Time' p = Bar( dfs[interesante], title="Gender By Inglehart-Welzel Culture {}".format(title_suffix), xlabel="Culture", ylabel= "Total gendered biographies (Red), Female Percentage *1,000,00(Green)") #bar.yaxis.formatter = NumeralTickFormatter(format="0.0%") js_filename = "gender_by_culture_{}.js".format(newest_changes) output_path = "./files/assets/js/" script_path = "./assets/js/" # generate javascript plot and corresponding script tag js, tag = autoload_static(p, CDN, script_path + js_filename) with open(output_path + js_filename, 'w') as js_file: js_file.write(js) return {'plot_tag': tag, 'table_html': table_html}
def embedPlot_old(plot): """Embed plot method for older versions of bokeh""" from bokeh.resources import Resources from bokeh.embed import autoload_static fp = os.path.join(request.folder,'static/temp/') fp = os.path.join(fp, plot._id+".js") res = Resources("relative") res.js_files = ["../static/js/bokeh.min.js"] res.css_files = ["../static/css/bokeh.min.css"] jspath = os.path.join('../static/temp/', plot._id+".js") js,tag = autoload_static(plot, res, jspath) with open(fp, "w") as f: f.write(js) print return js,tag
def test_script_attrs(self, mock_uuid): mock_uuid.uuid4 = mock.Mock() mock_uuid.uuid4.return_value = 'uuid' js, tag = embed.autoload_static(_embed_test_plot, CDN, "some/path") html = bs4.BeautifulSoup(tag) scripts = html.findAll(name='script') self.assertEqual(len(scripts), 1) attrs = scripts[0].attrs self.assertTrue(set(attrs), set(['src', 'data-bokeh-model-id', 'async', 'id', 'data-bokeh-doc-id'])) self.assertEqual(attrs['async'], 'false') self.assertEqual(attrs['data-bokeh-doc-id'], 'uuid') self.assertEqual(attrs['data-bokeh-model-id'], str(_embed_test_plot._id)) self.assertEqual(attrs['src'], 'some/path')
def page_desc(module_desc): module_path, name = module_desc['file'], module_desc['name'] var_name = module_desc.get('var_name', None) plotting._default_document = Document() namespace = {} with open(module_path, "r") as module_file: code = compile(module_file.read(), module_path, "exec") eval(code, namespace) if var_name: if 'chart' in module_desc['file']: obj = namespace[var_name] objs = [obj.chart.plot] else: objs = [namespace[var_name]] else: objs = plotting.curdoc().context.children embed_snippet = "" for i, obj in enumerate(objs): filename = name + "." + str(i) + ".js" js, tag = autoload_static( obj, Resources(mode="server", root_url=HOSTED_STATIC_ROOT), os.path.join(DETAIL_URL_ROOT, filename) ) embed_snippet += tag with open(os.path.join(SNIPPET_BUILD_DIR, filename), "w") as f: f.write(js) detail_snippet = highlight( open(module_path).read(), PythonLexer(), HtmlFormatter() ) return dict( name = name, embed_snippet = embed_snippet, detail_snippet = detail_snippet, detail_page_url = DETAIL_URL_ROOT + name + ".html", prev_detail_url = "", prev_detail_name = "", next_detail_url = "", next_detail_name ='', )
def wrapped_func(newest_changes): p, date_range, table_html, has_changes = plot_func(newest_changes) if has_changes: js_filename = "gender_by_{}_{}.js".format(characteristic, newest_changes) script_path = "./assets/js/" output_path = "./files/assets/js/" js, tag = autoload_static(p, CDN, script_path + js_filename) with open(output_path + js_filename, 'w') as js_file: js_file.write(js) else: tag, table_html = None, None return {'plot_tag': tag, 'table_html': table_html, 'date_range': date_range, 'has_changes': has_changes}
def graph(): db = mysql.connector.connect(user='******', password='******', host='10.0.51.21', database='SOC_Portal') cur = db.cursor(buffered=True) cur.execute('SELECT startDate, totalTime FROM PastTasks WHERE status="Complete" ORDER BY startDate ASC') dates = [] times = [] for item in cur: d = item[0] h,m,s = item[1].split(":") t = datetime.time(0,int(h),int(m)) dates.append(d) times.append(t) rows = cur.fetchall() df = pd.DataFrame([[ij for ij in i] for i in rows]) df.rename(columns={0: 'endDate', 1: 'totalTime'}, inplace = True); # prepare some data x = dates#df['endDate'] y = times#df['totalTime'] # create a new plot with a title and axis labels p = figure(title="User Completion Time", x_axis_type='datetime', x_axis_label = 'Date(M/D)', y_axis_type='datetime', y_axis_label='Average Completion Time' ) # add a line renderer with legend and line thickness p.line(x, y, color ='#FDC14A', line_width=3) # must be applied to the 1st element, not the axis itself #p.yaxis.formatter = DatetimeTickFormatter( # hourmin = ['%H:%M'], # hours = ['%H:%M']) # show the results output_file("Users.html") #show(p) js, tag = autoload_static(p, CDN, "/Users/zachauzenne/Desktop/DESKTOP/SOC_Portal_Site/templates/analystOverview.html")
def test_script_attrs(self, mock_uuid): mock_uuid.uuid4 = mock.Mock() mock_uuid.uuid4.return_value = 'uuid' js, tag = embed.autoload_static(_embed_test_plot, CDN, "some/path") html = bs4.BeautifulSoup(tag) scripts = html.findAll(name='script') self.assertEqual(len(scripts), 1) attrs = scripts[0].attrs self.assertTrue( set(attrs), set([ 'src', 'data-bokeh-model-id', 'async', 'id', 'data-bokeh-doc-id' ])) self.assertEqual(attrs['async'], 'false') self.assertEqual(attrs['data-bokeh-doc-id'], 'uuid') self.assertEqual(attrs['data-bokeh-model-id'], str(_embed_test_plot._id)) self.assertEqual(attrs['src'], 'some/path')
def plot(newest_changes): filelist = os.listdir('/home/maximilianklein/snapshot_data/{}/'.format(newest_changes)) culture_file = [f for f in filelist if f.startswith('culture')][0] if newest_changes == 'newest-changes': date_range = culture_file.split('culture-index-from-')[1].split('.csv')[0].replace('-',' ') print(date_range) csv_to_read = '/home/maximilianklein/snapshot_data/{}/{}'.format(newest_changes,culture_file) df = pandas.DataFrame.from_csv(csv_to_read) no_gender_perc = df['nan'].sum() / df.sum().sum() del df['nan'] df['total'] = df.sum(axis=1) df['nonbin'] = df['total'] - df['male'] - df['female'] df['fem_per'] = df['female'] / (df['total']) df['nonbin_per'] = df['nonbin'] / df['total'] df['fem_per_million'] = df['fem_per'] * 1000000 df['nonbin_per_million'] = df['nonbin_per'] * 1000000 dfs = df.sort('female') interesante = ['female','male','nonbin'] htmltable = dfs[interesante] htmltable.columns=['Women','Men', 'Non-binary'] table_html = htmltable.to_html(na_rep='n/a') title_suffix = 'Changes since {}'.format(date_range) if newest_changes == 'newest-changes' else 'All Time' p = Bar(dfs[interesante], title="Gender By Inglehart-Welzel Culture {}".format(title_suffix), xlabel = "Culture", ylabel = "Total gendered biographies (Red), Female Percentage *1,000,00(Green)") #bar.yaxis.formatter = NumeralTickFormatter(format="0.0%") js_filename = "gender_by_culture_{}.js".format(newest_changes) output_path = "./files/assets/js/" script_path = "./assets/js/" # generate javascript plot and corresponding script tag js, tag = autoload_static(p, CDN, script_path + js_filename) with open(output_path + js_filename, 'w') as js_file: js_file.write(js) return {'plot_tag':tag, 'table_html':table_html}
def _process_script(source, filename, env, js_name, use_relative_paths=False): # Explicitly make sure old extensions are not included until a better # automatic mechanism is available Model._clear_extensions() # quick and dirty way to inject Google API key if "GOOGLE_API_KEY" in source: GOOGLE_API_KEY = getenv("GOOGLE_API_KEY") if GOOGLE_API_KEY is None: if env.config.bokeh_missing_google_api_key_ok: GOOGLE_API_KEY = "MISSING_API_KEY" else: raise SphinxError( "The GOOGLE_API_KEY environment variable is not set. Set GOOGLE_API_KEY to a valid API key, " "or set bokeh_missing_google_api_key_ok=True in conf.py to build anyway (with broken GMaps)" ) run_source = source.replace("GOOGLE_API_KEY", GOOGLE_API_KEY) else: run_source = source c = ExampleHandler(source=run_source, filename=filename) d = Document() # We may need to instantiate deprecated objects as part of documenting # them in the reference guide. Suppress any warnings here to keep the # docs build clean just for this case with warnings.catch_warnings(): if "reference" in env.docname: warnings.filterwarnings("ignore", category=BokehDeprecationWarning) c.modify_document(d) if c.error: raise RuntimeError(c.error_detail) resources = get_sphinx_resources() js_path = join(env.bokeh_plot_auxdir, js_name) js, script = autoload_static(d.roots[0], resources, js_name) with open(js_path, "w") as f: f.write(js) return (script, js, js_path, source)
def simple_plot(plot, tmp_dir): js_static_js = "static-flask-bokeh/js/" js_static_css = "static-flask-bokeh/css/" js_filename = plot._id + ".js" js_path = tmp_dir + js_filename res = Resources() res.mode = "server" res.js_files = [js_static_js + "bokeh-0.4.min.js"] res.css_files = [js_static_css + "bokeh-0.4.min.css"] js, tag = autoload_static(plot, res, js_path) with open(js_path, "w") as f: f.write(js) print("Path: %s" % js_path) print("Wrote %s" % js_filename) return tag, plot._id
def render_plot(): import numpy as np from bokeh.embed import autoload_static from bokeh.plotting import figure from bokeh.resources import CDN N = 4000 x = np.random.random(size=N) * 100 y = np.random.random(size=N) * 100 radii = np.random.random(size=N) * 1.5 colors = [ "#%02x%02x%02x" % (int(r), int(g), 150) for r, g in zip(50 + 2 * x, 30 + 2 * y) ] TOOLS = "resize,crosshair,pan,wheel_zoom,box_zoom,reset,tap,previewsave,box_select,poly_select,lasso_select" p = figure(tools=TOOLS) p.scatter(x, y, radius=radii, fill_color=colors, fill_alpha=0.6, line_color=None) js, tag = autoload_static(p, CDN, "http://localhost:%s/plot.js" % port) html = """ <html> <head> <title>color_scatter example</title> </head> <body> %s </body> </html> """ % tag return html, js
def plotsprl(events): import numpy as np from bokeh.plotting import figure, output_file, show from bokeh.models import Range1d # Skip the first point because it can be troublesome theta = np.linspace(0, 80 * np.pi, 100000)[1:] theta2 = np.linspace(0, 90 * np.pi, 100000)[1:] # Compute the radial coordinates for some different spirals arch = theta # Archimedean arch2 = theta2 # Now compute the X and Y coordinates (polar mappers planned for Bokeh later) arch_x = arch * np.cos(theta) arch_y = arch * np.sin(theta) arch2_x = arch2 * np.cos(theta) arch2_y = arch2 * np.sin(theta) spiral = figure(plot_width=400, plot_height=400, title="GoldenRatio", x_range=Range1d(start=-50, end=50), y_range=Range1d(start=-50, end=50)) spiral.xgrid.grid_line_color = None spiral.ygrid.grid_line_color = None spiral.line(arch_x, arch_y, color="#c1ff55", line_width=4) spiral.line(arch2_x, arch2_y, color="#b7feea", line_width=10) output_file("lines.html") show(spiral) # show the plot js, tag = autoload_static( spiral, CDN, '/' + filepath + '?id=' + str(randint(1, 1000000))) with open(filepath, 'w') as f: f.write(js) return js, tag
def make_snippet(plot): # js_static_js = "static/js/" js_static_js = "/usr/lib/python3.4/site-packages/bokeh/server/static/js/" # js_static_css = "static/css/" js_static_css = "/usr/lib/python3.4/site-packages/bokeh/server/static/css/" # js_filename = plot._id + ".js" # js_path = js_static_js + js_filename js_path = "output.js" res = Resources("relative") res.js_files = [js_static_js + "bokeh.min.js"] res.css_files = [js_static_css + "bokeh.min.css"] js, tag = autoload_static(plot, res, js_path) with open(js_path, "w") as f: f.write(js) print("Wrote %s" % js_path) return tag, plot._id
def render_plot(): import numpy as np from bokeh.embed import autoload_static from bokeh.plotting import figure from bokeh.resources import CDN N = 4000 x = np.random.random(size=N) * 100 y = np.random.random(size=N) * 100 radii = np.random.random(size=N) * 1.5 colors = [ "#%02x%02x%02x" % (int(r), int(g), 150) for r, g in zip(50+2*x, 30+2*y) ] TOOLS="resize,crosshair,pan,wheel_zoom,box_zoom,reset,tap,save,box_select,poly_select,lasso_select" p = figure(tools=TOOLS) p.scatter(x, y, radius=radii, fill_color=colors, fill_alpha=0.6, line_color=None) js, tag = autoload_static(p, CDN, "http://localhost:%s/plot.js" % port) html = """ <html> <head> <title>color_scatter example</title> </head> <body> %s </body> </html> """ % tag return html, js
def get(self, request, *args, **kwargs): return self.render_to_json_response({'plot': u''}) # measurement_type_pk = kwargs.get('measurement_type_pk') # measurement_type = MeasurementType.objects.get(pk=measurement_type_pk) collection = Collection.objects.get(pk=kwargs.get('pk')) units = Unit.objects.filter(measurements__match={'measurement_type': measurement_type.pk, 'active': True}, pk__in=[unit.pk for unit in collection.units], active=True) if units: bk.hold() bk.figure(x_axis_type="datetime", tools="pan,wheel_zoom,box_zoom,reset,previewsave") colors = self.get_colors(len(units)) for i, unit in enumerate(units): measurements = [(measurement.created_at, measurement.value) for measurement in unit.measurements if measurement.active and measurement.measurement_type == measurement_type] measurements.sort(key=lambda measurement: measurement[0]) data = { 'date': [measurement[0] for measurement in measurements], 'value': [measurement[1] for measurement in measurements] } bk.line(np.array(data['date']), data['value'], color=colors[i], line_width=2, legend=unit.__unicode__()) bk.grid().grid_line_alpha = 0.3 xax, yax = bk.axis() xax.axis_label = ugettext('Date') yax.axis_label = ugettext('Values') plot = bk.curplot() bk.get_default_color() plot.title = ugettext('Measurements type') # plot.title = ugettext('Measurements type {}'.format(measurement_type.__unicode__())) js, tag = autoload_static(plot, Resources(mode='server', root_url=settings.STATIC_URL), "") return self.render_to_json_response({'plot': u'{}<script>{}</script>'.format(tag, js)}) return self.render_to_json_response(ugettext('Not found'), status=404)
def _process_script(source, filename, auxdir, js_name): # This is lame, but seems to be required for python 2 source = CODING.sub("", source) # quick and dirty way to inject Google API key if "GOOGLE_API_KEY" in source: run_source = source.replace("GOOGLE_API_KEY", GOOGLE_API_KEY) else: run_source = source c = ExampleHandler(source=run_source, filename=filename) d = Document() c.modify_document(d) if c.error: raise PlotScriptError(c.error_detail) script_path = join("/scripts", js_name).replace('<<string>>', 'string') js_path = join(auxdir, js_name).replace('<<string>>', 'string') js, script = autoload_static(d.roots[0], resources, script_path) with open(js_path, "w") as f: f.write(js) return (script, js, js_path, source)
from bokeh.resources import CDN from bokeh.plotting import figure from bokeh.embed import autoload_static plot = figure() plot.circle([1,2], [3,4]) js, tag = autoload_static(plot, CDN, "some/path") print js print tag
def bladder_report(output_filename, name, input_ply, input_csv): title = name f = open(output_filename, 'w') f.write("""<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title> {} </title> </head> <body> """.format(title)) df = pd.read_csv(input_csv) df = df.loc[df['label'] > 0] p = figure(plot_width=250, plot_height=250, x_axis_label='area', y_axis_label='aniso') line1 = p.circle('area', 'aniso', size=2, source=df) p1 = figure(plot_width=250, plot_height=250, x_axis_label='area') hist, edges = np.histogram(df['area'], density=True, bins=50) p1.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:]) p2 = figure(plot_width=250, plot_height=250, x_axis_label='aniso') hist, edges = np.histogram(df['aniso'], density=True, bins=50) p2.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:]) c = gridplot([[p, p1, p2]]) js, tag = autoload_static( c, CDN, os.path.splitext(os.path.basename(output_filename))[0] + '-data.js') g = open(os.path.splitext(output_filename)[0] + '-data.js', 'w') g.write(js) f.write('<h2>' + title + '</h2>\n') f.write('<a href="' + name + '-3d-overlay.html"> 3D View </a>\n') f.write('<table>\n') f.write('<tr>\n') for heading in ['maxproj', 'labels', 'relarea', 'abslogarea', 'aniso']: f.write('<th>' + heading + '</th>\n') f.write('</tr>\n') f.write('<tr>\n') f.write('<td><a href="../maxproj/' + name + '.png"><img src="../maxproj/' + name + '-thumb.png" height="200px"></a></td>') f.write('<td><a href="../image_labels/' + name + '.png"><img src="../image_labels/' + name + '-thumb.png" height="200px"></a></td>') f.write('<td><a href="../image_relarea/' + name + '.png"><img src="../image_relarea/' + name + '-thumb.png" height="200px"></a></td>') f.write('<td><a href="../image_abslogarea/' + name + '.png"><img src="../image_abslogarea/' + name + '-thumb.png" height="200px"></a></td>') f.write('<td><a href="../image_aniso/' + name + '.png"><img src="../image_aniso/' + name + '-thumb.png" height="200px"></a></td>') f.write('</tr>\n') f.write('</table>\n') f.write(tag) df.to_html(f) f.write('</body>\n') with open(template_3d, 'r') as g2: s = g2.read() t = Template(s) with open(output_filename[:-5] + '-3d.html', 'w') as f2: f2.write( t.substitute({ 'name': name, 'filename': name + '.ply', 'csvname': '../cell_data/' + name + '.csv' })) with open(template_overlay, 'r') as g2: s = g2.read() t = Template(s) with open(output_filename[:-5] + '-3d-overlay.html', 'w') as f3: f3.write( t.substitute({ 'name': name, 'filename': name + '.ply', 'filename_extra': name + '_overlay.ply', 'csvname': '../cell_data/' + name + '.csv', 'default_aniso_min': 0, 'default_aniso_max': 1, 'default_area_min': 25, 'default_area_max': 2500, }))
def iplot(self, plottype='linear', jspath=None, title='', browser='chrome', tools=TOOLS, x_axis_type='datetime', line_width=2, background_fill= '#eeeff0', alpha=0.7, plot_width=900, plot_height=400, xlabel='', ylabel='', style='o-'): """Writes javascript in given location, embeds it in a html saved in same location, and opens it in a browser Example ------- >>> import pandas as pd >>> import pandasaddons >>> rdf = pd.RandomDataFrame(index_type='datetime') >>> rdf.iplot() >>> rdf = pd.RandomDataFrame(index_type='linear')-0.5 >>> rdf.iplot(plottype='heatmap', xlabel='x', ylabel='y') """ if plottype.lower() == 'heatmap': plot = heatmap_df(self, tools=tools, title=title, alpha=alpha, plot_width=plot_width, plot_height=plot_height, xlabel=xlabel, ylabel=ylabel, x_axis_location='above') else: plot = plot_df(self, tools=tools, title=title, x_axis_type=x_axis_type, line_width=line_width, background_fill=background_fill, alpha=alpha, style=style, plot_width=plot_width, plot_height=plot_height, xlabel=xlabel, ylabel=ylabel) filename = str(uuid.uuid4()) this_jspath = jspath if jspath else os.environ['TMP'] jsfilename = os.path.join(this_jspath, filename+'.js') htmlfilename = os.path.join(this_jspath, filename+'.html' ) js, tag = autoload_static(plot, CDN, script_path=jsfilename) with open(jsfilename, 'w') as f: f.write(js) html = '<html><div>'+tag+'</div></html>' with open(htmlfilename, 'w') as f: f.write(html) os.system('start {browser}.exe "{htmlfilename}"'.format(**locals()))
def index(request): # print(div_tag,div_script) username = '******' logintime = '0' if 'user_name' in request.COOKIES: username = request.COOKIES['user_name'] else: return redirect('./../?usr=0', request) if 'user_name' in request.COOKIES: username = request.COOKIES['user_name'] if 'login_time' in request.COOKIES: logintime = request.COOKIES['login_time'] if request.method != 'POST': print('not post') return render(request, 'findex.html', locals()) if request.method == 'POST': print('post') count = int(request.POST.get('count')) xl = int(request.POST.get('xl')) xr = int(request.POST.get('xr')) yl = int(request.POST.get('yl')) yr = int(request.POST.get('yr')) print(xl) print(xr) print(yl) print(yr) fig = plt.figure() ax = fig.add_subplot(111) fig.subplots_adjust(top=0.85) plt.grid(True) TOOLS = 'box_select,resize,reset,pan,tap,wheel_zoom,save,hover' bplot = figure(plot_width=640, plot_height=480, tools=TOOLS, toolbar_location='above') print(count) x = [] y = [] z = [] name = [] color = [] contourplot = [] arr = [0] * count print(arr) for i in arange(1, count + 1): tempr = 'result' + str(i) tempo = 'output' + str(i) tempc = 'color' + str(i) result = str(request.POST.get(tempr)) fun = request.POST.get(tempo) color.append(request.POST.get(tempc)) print(fun) print(request.POST.get(tempc)) print(result) print(tempc) name.append(fun) a = [] b = [] c = [] if ('x' in result and 'y' in result): func = lambda x, y: eval(result) contourplot.append(result) arr[i - 1] = 1 for i in arange(xl, xr + 1, 0.1): a.append(i) for j in arange(yl, yr + 1, 0.1): b.append(j) for i in arange(xl, xr + 1, 0.1): for j in arange(yl, yr + 1, 0.1): c.append(func(i, j)) x.append(a) y.append(b) print(a) print(b) print(c) c = np.array(c) c = c.reshape((len(a), len(b))) z.append(c) elif 'x' in result: func = lambda x: eval(result) for i in arange(xl, xr + 1, 0.1): a.append(i) b.append(func(i)) x.append(a) y.append(b) else: func = lambda y: eval(result) for j in arange(yl, yr + 1, 0.1): a.append(j) b.append(func(j)) x.append(a) y.append(b) ddata = [] k = 0 for i in range(0, len(x)): if arr[i]: plt.contour(x[i], y[i], z[k], [1]) k += 1 else: plt.plot(x[i], y[i], marker='.', markersize=2, alpha=1, color=color[i], label=name[i]) bplot.line(x[i], y[i], color=color[i], legend=name[i]) plt.legend(loc=0) fig1 = plt.gcf() if (FileSystemStorage('fplot/static/img/').exists(username + logintime + '.png')): os.remove('fplot/static/img/' + username + logintime + 'fplot.png') fig1.savefig('fplot/static/img/' + username + logintime + 'fplot.png', dpi=200) fig1.savefig('fplot/static/img/' + username + logintime + 'fplot.jpg', dpi=200) fig1.savefig('fplot/static/img/' + username + logintime + 'fplot.eps', dpi=200) fig1.savefig('fplot/static/img/' + username + logintime + 'fplot.pdf', dpi=200) fig1.savefig('fplot/static/img/' + username + logintime + 'fplot.svg', dpi=200) fig1.savefig('fplot/static/img/' + username + logintime + 'fplot.tiff', dpi=200) fig1.savefig('fplot/static/img/' + username + logintime + 'fplot.ps', dpi=200) fig1.savefig('fplot/static/img/' + username + logintime + 'fplot.svgz', dpi=200) # fig1.savefig('graph/static/img/test.pgf', dpi=200)#latex not installed sudo apt-get install texlive-xetex fig1.savefig('fplot/static/img/' + username + logintime + 'fplot.jpeg', dpi=200) # fig1.savefig('graph/static/img/test.raw', dpi=200)#if needed fig1.savefig('fplot/static/img/' + username + logintime + 'fplot.tif', dpi=200) saved = True dis = 'static/img/' + username + logintime + 'fplot.png' # shutil.copyfile('graph/static/img/'+username+logintime+'.png', dis) saved = True imagelink = 'img/' + username + logintime + 'fplot.png' filelink = 'xlsx/' + username + logintime + 'fplot.xlsx' bplot.legend.location = "top_left" bplot.legend.background_fill_color = "white" bplot.legend.background_fill_alpha = 0.5 div_script, div_tag = autoload_static(bplot, CDN, "js") image = 'img/' + username + logintime + 'fplot' plotgraph = 1 tabled = 1 return render(request, 'findex.html', locals()) return render(request, 'findex.html', locals())
colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'} colors = [colormap[x] for x in flowers['species']] p = figure(title="Iris Morphology") p.xaxis.axis_label = 'Petal Length' p.yaxis.axis_label = 'Petal Width' p.circle(flowers["petal_length"], flowers["petal_width"], color=colors, fill_alpha=0.2, size=10) return p if __name__ == '__main__': print( 'Opening Tornado app with embedded Bokeh plot on http://localhost:8080/' ) js, script = autoload_static(make_plot(), CDN, "embed.js") app = Application([(r"/", IndexHandler, dict(script=script)), (r"/embed.js", JSHandler, dict(js=js))]) app.listen(8080) io_loop = IOLoop.current() io_loop.add_callback(view, "http://localhost:8080/") io_loop.start()
def test_return_type(self): r = embed.autoload_static(_embed_test_plot, CDN, "some/path") self.assertEqual(len(r), 2)
# NEW: create a new plot and share only one range s3 = figure(width=350, height=350, x_range=s1.x_range, title=None) s3.square(x, y2, size=10, color="olive", alpha=0.5) s3.toolbar_location = None; web_s1_path = "./plots/linked-1.js" web_s2_path = "./plots/linked-2.js" web_s3_path = "./plots/linked-3.js" local_s1_path = os.path.join("..", "..", "build", "plots", "linked-1.js") local_s2_path = os.path.join("..", "..", "build", "plots", "linked-2.js") local_s3_path = os.path.join("..", "..", "build", "plots", "linked-3.js") html_path = os.path.join("..", "..", "build", "index.html") tags = [] js, tag = autoload_static(s1, CDN, web_s1_path) script = open(local_s1_path, "w") script.write(js) script.close() tags.append(tag) js, tag = autoload_static(s2, CDN, web_s2_path) script = open(local_s2_path, "w") script.write(js) script.close() tags.append(tag) js, tag = autoload_static(s3, CDN, web_s3_path) script = open(local_s3_path, "w") script.write(js) script.close() tags.append(tag)
def plot(newest_changes): filelist = os.listdir('/home/maximilianklein/snapshot_data/{}/'.format(newest_changes)) site_linkss_file = [f for f in filelist if f.startswith('worldmap')][0] if newest_changes == 'newest-changes': date_range = site_linkss_file.split('worldmap-index-from-')[1].split('.csv')[0].replace('-',' ') print(date_range) csv_to_read = '/home/maximilianklein/snapshot_data/{}/{}'.format(newest_changes,site_linkss_file) df = pandas.DataFrame.from_csv(csv_to_read) major = df[df['total'] > 100] table_html = major.sort('Score', ascending=False).to_html(max_rows=10) # https://github.com/chdoig/pyladiesatx-bokeh-tutorial world_countries = wc.data.copy() country_xs = [world_countries[code]['lons'] for code in world_countries] country_ys = [world_countries[code]['lats'] for code in world_countries] country_names = [world_countries[code]['name'] for code in world_countries] def lookup_wigi(code): try: return df.ix[code]['Score'] except KeyError: return -1 index_vals = np.array([lookup_wigi(code) for code in world_countries]) def fmt(c): return int(np.nan_to_num(c)) colors = [ "#%02x%02x%02x" % (fmt(r), fmt(g), fmt(b)) for r, g, b in zip(np.floor(250*(1-index_vals)), np.floor(200*(1-index_vals)), np.floor(100*index_vals))] source = ColumnDataSource( data=dict( name=country_names, wigi_index=[str(idx) for idx in index_vals] ) ) # setup widgets TOOLS = "pan,wheel_zoom,box_zoom,reset,hover,save" title_suffix = 'Changes since {}'.format(date_range) if newest_changes == 'newest-changes' else 'All Time' p = figure(title="Gender by Country {}".format(title_suffix), tools=TOOLS) p.patches(country_xs, country_ys, fill_color=colors, source=source) hover = p.select(dict(type=HoverTool)) hover.point_policy = "follow_mouse" hover.tooltips = OrderedDict([ ("wigi", "@wigi_index"), ("Country", "@name"), ]) js_filename = "gender_by_country_{}.js".format(newest_changes) script_path = "./assets/js/" output_path = "./files/assets/js/" # generate javascript plot and corresponding script tag js, tag = autoload_static(p, CDN, script_path + js_filename) with open(output_path + js_filename, 'w') as js_file: js_file.write(js) return {'plot_tag':tag, 'table_html':table_html}
def javascript(self) -> str: """javascript to save""" if self._javascript is None: self._javascript, self._source = autoload_static( self.figure, self.bokeh_source, self.file_name) return self._javascript
p.grid.grid_line_color = None hover = p.select(dict(type=HoverTool)) hover.tooltips = OrderedDict( [ ("name", "@name"), ("atomic number", "@atomic_number"), ("type", "@type"), ("atomic mass", "@mass"), ("CPK color", "$color[hex, swatch]:cpk"), ("electronic configuration", "@electronic"), ] ) web_path = "./plots/periodic.js" local_path = os.path.join("..", "..", "build", "plots", "periodic.js") html_path = os.path.join("..", "..", "build", "index.html") js, tag = autoload_static(p, CDN, web_path) script = open(local_path, "w") script.write(js) script.close() html_file = open(html_path, "r") html = html_file.read() html_file.close() html_file = open(html_path, "w") html_file.write(html.replace("PERIODIC-PLOT", tag)) html_file.close()
def source(self) -> str: """The HTML fragment to export""" if self._source is None: self._javascript, self._source = autoload_static( self.figure, self.bokeh_source, self.file_name) return self._source
def index(request): # print(div_tag,div_script) username = '******' logintime = '0' if 'user_name' in request.COOKIES: username = request.COOKIES['user_name'] else: return redirect('./../?usr=0', request) if 'user_name' in request.COOKIES: username = request.COOKIES['user_name'] if 'login_time' in request.COOKIES: logintime = request.COOKIES['login_time'] if request.method != 'POST': print('not post') return render(request, 'pindex.html', locals()) if request.method == 'POST': print('post') count = int(request.POST.get('count')) tl = int(request.POST.get('tl')) tr = int(request.POST.get('tr')) print(tl) print(tr) fig = plt.figure(figsize=(7, 7)) ax = fig.add_subplot(111) fig.subplots_adjust(top=0.85) plt.grid(True) TOOLS = 'box_select,resize,reset,pan,tap,wheel_zoom,save,hover' bplot = figure(plot_width=640, plot_height=480, tools=TOOLS, toolbar_location='above') print(count) x = [] y = [] name = [] color = [] contourplot = [] arr = [0] * count print(arr) for i in arange(1, count + 1): tempxr = 'resultx' + str(i) tempxo = 'outputx' + str(i) tempyr = 'resulty' + str(i) tempyo = 'outputy' + str(i) tempc = 'color' + str(i) resultx = str(request.POST.get(tempxr)) resulty = str(request.POST.get(tempyr)) funx = request.POST.get(tempxo) funy = request.POST.get(tempyo) color.append(request.POST.get(tempc)) print(funx) print(funy) print(request.POST.get(tempc)) print(resultx) print(resulty) print(tempc) name.append('x:' + (funx) + ';\ny:' + funy) funcx = lambda t: eval(resultx) funcy = lambda t: eval(resulty) t = np.arange(tl, tr, 0.1) a = funcx(t) b = funcy(t) x.append(a) y.append(b) ddata = [] k = 0 for i in range(0, len(x)): plt.plot(x[i], y[i], marker='.', markersize=2, alpha=1, color=color[i], label=name[i]) bplot.line(x[i], y[i], color=color[i], legend=name[i]) plt.legend(loc=0) fig1 = plt.gcf() if (FileSystemStorage('pplot/static/img/').exists(username + logintime + '.png')): os.remove('pplot/static/img/' + username + logintime + 'pplot.png') fig1.savefig('pplot/static/img/' + username + logintime + 'pplot.png', dpi=200) fig1.savefig('pplot/static/img/' + username + logintime + 'pplot.jpg', dpi=200) fig1.savefig('pplot/static/img/' + username + logintime + 'pplot.eps', dpi=200) fig1.savefig('pplot/static/img/' + username + logintime + 'pplot.pdf', dpi=200) fig1.savefig('pplot/static/img/' + username + logintime + 'pplot.svg', dpi=200) fig1.savefig('pplot/static/img/' + username + logintime + 'pplot.tiff', dpi=200) fig1.savefig('pplot/static/img/' + username + logintime + 'pplot.ps', dpi=200) fig1.savefig('pplot/static/img/' + username + logintime + 'pplot.svgz', dpi=200) # fig1.savefig('graph/static/img/test.pgf', dpi=200)#latex not installed sudo apt-get install texlive-xetex fig1.savefig('pplot/static/img/' + username + logintime + 'pplot.jpeg', dpi=200) # fig1.savefig('graph/static/img/test.raw', dpi=200)#if needed fig1.savefig('pplot/static/img/' + username + logintime + 'pplot.tif', dpi=200) saved = True dis = 'static/img/' + username + logintime + 'pplot.png' # shutil.copyfile('graph/static/img/'+username+logintime+'.png', dis) saved = True imagelink = 'img/' + username + logintime + 'pplot.png' filelink = 'xlsx/' + username + logintime + 'pplot.xlsx' bplot.legend.location = "top_left" bplot.legend.background_fill_color = "white" bplot.legend.background_fill_alpha = 0.5 div_script, div_tag = autoload_static(bplot, CDN, "js") image = 'img/' + username + logintime + 'pplot' plotgraph = 1 tabled = 1 return render(request, 'pindex.html', locals())
self.js = js def get(self): self.write(self.js) def make_plot(): colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'} colors = [colormap[x] for x in flowers['species']] p = figure(title = "Iris Morphology") p.xaxis.axis_label = 'Petal Length' p.yaxis.axis_label = 'Petal Width' p.circle(flowers["petal_length"], flowers["petal_width"], color=colors, fill_alpha=0.2, size=10) return p if __name__ == '__main__': print('Opening Tornado app with embedded Bokeh plot on http://localhost:8080/') js, script = autoload_static(make_plot(), CDN, "embed.js") app = Application([ (r"/", IndexHandler, dict(script=script)), (r"/embed.js", JSHandler, dict(js=js)) ]) app.listen(8080) io_loop = IOLoop.current() io_loop.add_callback(view, "http://localhost:8080/") io_loop.start()
def plotradial(events, userid): rating_color = OrderedDict([("Actualfear", "#c1ff55"), ("Predictedfear", "#b7feea")]) xr = [x.title for x in events] i = [i for i, j in enumerate(events)] y1 = [y.prefearfactor for y in events] y2 = [y.postfearfactor for y in events] data = { 'prefearfactor': pd.Series(y1, index=i), 'postfearfactor': pd.Series(y2, index=i) } df = pd.DataFrame(data) width = 500 #400 height = 420 #350 inner_radius = 60 #50 outer_radius = 440 - 20 #360 - 10 minr = 0 maxr = 20 min_pixel = (outer_radius - inner_radius) / (maxr - minr) big_angle = 2.0 * np.pi / (len(df)) x = np.zeros(len(df)) y = np.zeros(len(df)) #------------------------------------------------------------------------------------ output_file("radialchart.html", title="radial.py example") p = figure(plot_width=width, plot_height=height, title="Imagined vs real fear", x_axis_type=None, y_axis_type=None, toolbar_location=None, x_range=[-420, 420], y_range=[-420, 420], min_border=0, outline_line_color=None, background_fill="#f8f8f8", border_fill="#f8f8f8") # small wedges angles = np.pi / 2 - big_angle / 2 - df.index * big_angle p.annular_wedge(x, y, inner_radius, inner_radius + min_pixel * (df.postfearfactor), -big_angle + angles, angles, color=rating_color['Actualfear']) p.annular_wedge(x, y, inner_radius + min_pixel * (df.postfearfactor), inner_radius + min_pixel * (df.postfearfactor) + min_pixel * (df.prefearfactor), -big_angle + angles, angles, color=rating_color['Predictedfear']) # radial axes p.annular_wedge(x, y, inner_radius, outer_radius, -big_angle + angles, -big_angle + angles, color="#c2c2d6") # [x1,x2], [y1,y2] is for rect1 and rect2 x and y start positions (y is inverted) p.rect([180, 180], [380, 340], width=30, height=20, color=list(rating_color.values())) #similarly for the legend text p.text([200, 200], [365, 325], text=list(rating_color.keys()), text_font_size="10pt", text_align="left", text_baseline="bottom") p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None #generating unique filenames by- adding userid to a rolledindex """ global rollingindex userfilepath = filepath+str(userid)+str(rollingindex.next())+'.js' """ userfilepath = filepath + str(userid) + '.js' js, tag = autoload_static( p, CDN, '/' + userfilepath + '?id=' + str(randint(1, 1000000))) with open(userfilepath, 'w') as f: f.write(js) return js, tag
def plot(newest_changes): ra_len = 1 #rolling average lenght dox = pandas.DataFrame() interesante = ['female','male','nonbin'] for l in ['b', 'd']: acro = 'do'+l filelist = os.listdir('/home/maximilianklein/snapshot_data/{}/'.format(newest_changes)) dox_list = [f for f in filelist if f.startswith(acro)] dox_file = dox_list[0] if newest_changes == 'newest-changes': date_range = dox_file.split('{}-index-from-'.format(acro))[1].split('.csv')[0].replace('-',' ') csv_to_read = '/home/maximilianklein/snapshot_data/{}/{}'.format(newest_changes,dox_file) df = pandas.DataFrame.from_csv(csv_to_read) del df['nan'] df['total'] = df.sum(axis=1) df['nonbin'] = df['total'] - df['male'] - df['female'] df['fem_per'] = df['female'] / (df['total']) df['nonbin_per'] = df['nonbin'] / df['total'] for inte in interesante: dox['{}-{}'.format(acro, inte)] = df[inte] #ra = pandas.rolling_mean(df['fem_per'], ra_len) #dox[acro] = ra time_range = (1400, 2015) dox = dox[time_range[0]: time_range[1]] '''dox['Date'] = [dateutil.parser.parse(str(int(x))) for x in dox['dob'].keys()]''' tups = zip(['Date of Birth']*3 + ['Date of Death']*3, ['Women', 'Men', 'Non-binary']* 2) labs = ['-'.join(x) for x in tups] dox.columns = labs table_html = dox.to_html(max_rows=20, na_rep="n/a") title_suffix = 'Changes since {}'.format(date_range) if newest_changes == 'newest-changes' else 'All Time' p = Line(dox, legend=True, title="Female Ratios {}".format(title_suffix)) #p.below[0].formatter.formats = dict(years=['%Y']) ''' nonbindox = nonbindox[time_range[0]: time_range[1]] nonbindox['Date'] = [dateutil.parser.parse(str(int(x))) for x in nonbindox['dob'].keys()] p2 = TimeSeries(nonbindox[['dob','dod','Date']], index='Date', legend=True, title="Non Binary Ratios ".format(title_suffix)) p2.below[0].formatter.formats = dict(years=['%Y']) p = gridplot([[p1], [p2]], toolbar_location=None) ''' js_filename = "gender_by_dob_{}.js".format(newest_changes) script_path = "./assets/js/" output_path = "./files/assets/js/" # generate javascript plot and corresponding script tag js, tag = autoload_static(p, CDN, script_path + js_filename) with open(output_path + js_filename, 'w') as js_file: js_file.write(js) return {'plot_tag':tag, 'table_html':table_html}
# # <p> Below is a simple plot of stock closing prices </p> # # {{ script }} # # {{ div }} # #</body> # #</html> #""") p = make_figure(0) #figJS,figDiv = components(p) figJS, figDiv = autoload_static(p, CDN, '/static/js/plot.js') with open('static/js/plot.js', 'w') as f: f.write(figJS) #f.close() #import random #def plotData(): # j = random.randint(0,1000) # print j%3 # p = make_figure(j%3) # figJS, figDiv = autoload_static(p, CDN, '/static/js/plot.js') # with open('static/js/plot.js', 'w') as f: # f.write(figJS) # return figJS, figDiv ## f.close()