def digest(): data = json.loads(request.data) user_api = gen_api(ClassicalSubgroups.from_str(data["subgroup"]), data["n"]) tools = "pan,wheel_zoom,reset,save" graph_fig = bk.figure(match_aspect=True, title='Graph', tools=tools) graph_fig.sizing_mode = 'stretch_both' domain_fig = bk.figure(match_aspect=True, title='Domain', tools=tools) domain_fig.sizing_mode = 'stretch_both' user_api.plot_graph_on_bokeh(graph_fig) user_api.plot_domain_on_bokeh(domain_fig) generators = user_api.get_generators_str() graph_plot = json_item(graph_fig) domain_plot = json_item(domain_fig) response = { "graph": graph_plot, "domain": domain_plot, "generators": generators } return json.dumps(response)
def streamlit_bokeh_events(bokeh_plot=None, events="", key=None, debounce_time=1000, refresh_on_update=True, override_height=None): """Returns event dict Keyword arguments: bokeh_plot -- Bokeh figure object (default None) events -- Comma separated list of events dispatched by bokeh eg. "event1,event2,event3" (default "") debounce_time -- Time in ms to wait before dispatching latest event (default 1000) refresh_on_update -- Should the chart be re-rendered on refresh (default False) : Set to False if you are not updating the datasource at runtime override_height -- Override plot viewport height """ if key is None: raise ValueError("key can not be None.") div_id = "".join(choices(ascii_letters, k=16)) fig_dict = json_item(bokeh_plot, div_id) json_figure = json.dumps(fig_dict) component_value = _component_func( bokeh_plot=json_figure, events=events, key=key, _id=div_id, default=None, debounce_time=debounce_time, refresh_on_update=refresh_on_update, override_height=override_height ) return component_value
def main(args=None): """ Parse the arguments, get the data in a df, and create the plot :return: if requested, return the plot as JSON object """ if args is None: args = sys.argv[1:] parsed_args = parse_arguments(arguments=args) conn = connect_to_database(db_path=parsed_args.database) c = conn.cursor() scenario_id, scenario = get_scenario_id_and_name( scenario_id_arg=parsed_args.scenario_id, scenario_name_arg=parsed_args.scenario, c=c, script="energy_plot") tech_colors = get_tech_colors(c) tech_plotting_order = get_tech_plotting_order(c) energy_unit = get_unit(c, "energy") plot_title = "{}Energy by Period - {} - Stage {}".format( "{} - ".format(scenario) if parsed_args.scenario_name_in_title else "", parsed_args.load_zone, parsed_args.stage) plot_name = "EnergyPlot-{}-{}".format(parsed_args.load_zone, parsed_args.stage) df = get_plotting_data(conn=conn, scenario_id=scenario_id, load_zone=parsed_args.load_zone, stage=parsed_args.stage) source, x_col_reordered = process_stacked_plot_data( df=df, y_col="energy_mwh", x_col=["period"], category_col="technology") # Multi-level index in CDS will be joined into one column with "_" separator x_col_cds = "_".join(x_col_reordered) x_col_label = ", ".join([x.capitalize() for x in x_col_reordered]) plot = create_stacked_bar_plot(source=source, x_col=x_col_cds, x_label=x_col_label, y_label="Energy ({})".format(energy_unit), category_label="Technology", category_colors=tech_colors, category_order=tech_plotting_order, title=plot_title, ylimit=parsed_args.ylimit) # Show plot in HTML browser file if requested if parsed_args.show: show_plot(plot=plot, plot_name=plot_name, plot_write_directory=parsed_args.plot_write_directory, scenario=scenario) # Return plot in json format if requested if parsed_args.return_json: return json_item(plot, plot_name)
async def plot( *, resource_url: str = Query(..., title="Resource URL", description="URL to a NetCDF resource"), get: str = Query( ..., title="Query string", description= "Receive list of parameters or get the plot, specifying the variable name", regex='^(param|plot)$'), variable: str = Query(None, title="Variable name", description="String with the NetCDF Variable name"), metadata: bool = Query( False, title="metadata", description="If true add metadata tab to the plot widget")): if get == 'param': return get_variables(resource_url) if get == 'plot': data = get_data(resource_url, variable) # json_plot = create_plot(data) json_plot = create_page(data, metadata=metadata) json_data = json_item(json_plot, target='tsplot') return json_data
def marshall(proto, figure): """Construct a Bokeh chart object. See DeltaGenerator.bokeh_chart for docs. """ data = json_item(figure) proto.figure = json.dumps(data)
def plot1(): # copy/pasted from Bokeh Getting Started Guide - used as an example grouped = autompg.groupby("yr") mpg = grouped.mpg avg, std = mpg.mean(), mpg.std() years = list(grouped.groups) american = autompg[autompg["origin"] == 1] japanese = autompg[autompg["origin"] == 3] p = Figure(title="MPG by Year (Japan and US)") p.vbar(x=years, bottom=avg - std, top=avg + std, width=0.8, fill_alpha=0.2, line_color=None, legend="MPG 1 stddev") p.circle(x=japanese["yr"], y=japanese["mpg"], size=10, alpha=0.5, color="red", legend="Japanese") p.triangle(x=american["yr"], y=american["mpg"], size=10, alpha=0.3, color="blue", legend="American") p.legend.location = "top_left" return json.dumps(json_item(p, "myplot"))
def plot(): with open('temp.txt', 'r') as f: ticker, price_type = f.read().split(',') os.remove('temp.txt') p = make_plot(ticker, price_type) return json.dumps(json_item(p, "myplot"))
def bokeh_handler(request): data = request.get_json(silent=True) categories = [] counts = [] for item in data.items(): categories.append(item[0]) counts.append(int(item[1])) # Create the plot p = figure(x_range=categories, title="Fruit counts", toolbar_location=None, tools="") p.vbar(x=categories, top=counts, width=0.9) p.xgrid.grid_line_color = None p.y_range.start = 0 # Send message to server return { "statusCode": 200, "body": json.dumps(json_item(p)), "headers": { 'Access-Control-Allow-Headers': '*', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'OPTIONS,POST' } }
def comp_output(calc1, calc2, out_var='mettr'): ''' Function to create output for the COMP platform ''' out_table = calc1.summary_table(calc2, output_variable=out_var, output_type='csv') html_table = calc1.summary_table(calc2, output_variable=out_var, output_type='html') plt = calc1.grouped_bar(calc2, output_variable=out_var, include_title=True) plot_data = json_item(plt) comp_dict = { "renderable": [ { "media_type": "bokeh", "title": plt.title._property_values['text'], "data": plot_data }, { "media_type": "table", "title": out_var.upper() + " Summary Table", "data": html_table }, ], "downloadable": [ { "media_type": "CSV", "title": out_var.upper() + " Summary Table", "data": out_table.to_csv() } ] } return comp_dict
def get_charts(self, fields): plots = [] for field in fields: print(field) d = self.get_dist(col_name=field) print(d) data = pd.Series(d).reset_index(name='value').rename( columns={'index': 'field'}) data['angle'] = data['value'] / data['value'].sum() * 2 * pi data['color'] = Category20[len(d)] p = figure(title="Distribution of {}".format(field), plot_width=500, plot_height=500, tools="hover", toolbar_location=None, x_range=(-0.5, 1.0), tooltips="@field: @value") p.wedge(x=0, y=1, radius=0.4, start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), line_color="white", fill_color='color', legend_field='field', source=data) p.axis.axis_label = None p.axis.visible = False p.grid.grid_line_color = None plots.append(p) return json.dumps(json_item(gridplot(plots, ncols=2)))
def plotpred(): global y_pred global ecuacion x_pred = np.array(x) y_pre = np.array(y) p4 = np.poly1d(np.polyfit(x_pred, y_pre, 1)) ecuacion = str(p4) print("Predicción con factor de ", factor) print("tamaño x_pred: ", len(x_pred)) xp = np.linspace(0, len(x_pred) - 1, 1000 * factor) y_pred = p4(xp) p = figure(title="Vector " + str(vector), x_axis_label='Tiempo', y_axis_label='Dato aleatorio', plot_height=400, plot_width=1000) p.scatter(x, y, legend_label="Datos reales", line_width=2, line_color="blue") p.line(x_pred, y_pred, legend_label="Predicción", line_width=3, line_color="red") return json.dumps(json_item(p, "myplot"))
def crypto_plot(request): # get input variables if request.user.is_authenticated: user = request.user else: user = False coin = request.GET.get('coin_option') period = request.GET.get('time_option') currency = request.GET.get('currency_option') if coin == None: coin = "BTC" if period == None: period = "day" if currency == None: currency = "USD" print(coin, period, currency) # retrive data from cryptocompy api times, prices = get_graph_data(coin, currency, period) # generate graph PLOT_OPTIONS = dict(plot_width=800, plot_height=300, x_axis_type='datetime') SCATTER_OPTIONS = dict(size=12, alpha=0.5) try: color = coinList[coin] except KeyError: color = "firebrick" plot = figure(sizing_mode='scale_width', tools='pan', **PLOT_OPTIONS) #plot.scatter(x, data(), color=color, **SCATTER_OPTIONS) plot.line(times, prices, color=color, line_width=5) return HttpResponse(json.dumps(json_item(plot, "myplot")))
def get_per_app_usage(): total_time_spent = df.duration.sum() per_app_df = df.groupby('app_name')['duration'].sum().sort_values( ascending=False).to_frame().reset_index() per_app_df['angle'] = np.nan per_app_df['color'] = np.nan per_app_df.angle = per_app_df.duration.apply( lambda x: x.seconds / total_time_spent.seconds * 2 * pi) per_app_df['color'] = per_app_df.app_name.apply(lambda x: color_map[x]) per_app_df['duration_min'] = per_app_df['duration'].apply( lambda x: x.seconds // 60) p = figure(plot_height=400, plot_width=400, toolbar_location=None, tools="hover", tooltips="@app_name: @duration_min min") p.wedge(x=0, y=1, radius=0.9, start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), line_color="white", fill_color='color', source=per_app_df) p.axis.axis_label = None p.axis.visible = False p.grid.grid_line_color = None return json.dumps(json_item(p, "per_app_usage"))
def bokeh_chart(figure) -> V1EventChart: try: from bokeh.embed import json_item except ImportError: logger.warning(BOKEH_ERROR_MESSAGE) return UNKNOWN return V1EventChart(kind=V1EventChartKind.BOKEH, figure=json_item(figure))
def run( n, plot_title, plot_name, save_plot=False, save_json=False, no_gc=False, validate=False, ): results = [] for name, func in BENCHMARKS: print(f"- {name}...") dumps_time, loads_time = func(n, no_gc, validate) print(f" dumps: {dumps_time * 1e6:.2f} us") print(f" loads: {loads_time * 1e6:.2f} us") results.append((name, dumps_time, loads_time)) if save_plot or save_json: import json from bokeh.resources import CDN from bokeh.embed import file_html, json_item plot = make_plot(results, plot_title) if save_plot: with open(f"{plot_name}.html", "w") as f: html = file_html(plot, CDN, "Benchmarks") f.write(html) if save_json: with open(f"{plot_name}.json", "w") as f: data = json.dumps(json_item(plot)) f.write(data)
def heatmap(): data=pd.DataFrame( [ [1,0.2,0.3], [0.3,1,0.5], [-0.5,0.8,1]], columns=['a','b','c']) value=[] for x in data.apply(tuple): value.extend(x) absValue=[abs(number) for number in value] print(data) source={ 'x': [i for i in list(data.columns) for j in list(data.columns)], 'y': list(data.columns)*len(data.columns), 'value':value, 'abs':absValue } p=figure(title = "heatmap", sizing_mode="fixed", plot_width=600, plot_height=400,tools='pan,wheel_zoom,box_zoom,save,reset',x_range=list(data.columns),y_range=list(reversed(data.columns))) p.toolbar.logo=None from bokeh.models import LinearColorMapper from bokeh.palettes import inferno,YlOrRd,Magma,PuBu,Greys from bokeh.transform import transform crs=PuBu[9] crs.reverse() mapper = LinearColorMapper(palette=crs, low=min(absValue), high=max(absValue)) fontMapper=LinearColorMapper(palette=[Greys[5][0],Greys[5][4]], low=min(absValue), high=max(absValue)) p.rect(x="x", y="y", width=1, height=1, source=source, line_color=None, fill_color=transform('abs', mapper)) p.text(x="x", y="y",text='value', source=source,text_font_size='2em',text_font_style='bold',text_align='center',text_baseline='middle',text_color=transform('abs',fontMapper)) p.add_tools( HoverTool(tooltips = [('Value', '@value')]) ) return json.dumps(json_item(p))
def makeplot(): ticker = open('ticker.txt', 'r').read() h = requests.get( 'https://www.quandl.com/api/v3/datasets/WIKI/' + ticker + '/data.json?api_key=Qsspq9oLN8EGfAJzg93S&start_date=2015-10-01&end_date=2015-10-31' ).content h = json.loads(h)['dataset_data']['data'] dates = [] prices = [] for ob in h: dates.append(ob[0]) prices.append(ob[4]) dates = [parse(x) for x in dates] title = 'Quandl Wiki EOD Stock Prices for ' + ticker + ' during October 2015' p = figure(x_axis_type='datetime', title=title) p.line(dates, prices, line_width=2) p.xaxis.axis_label = 'Date' p.yaxis.axis_label = 'Closing Price' return json.dumps(json_item(p, 'myplot'))
def plot2(): # copy/pasted from Bokeh 'JavaScript Callbacks' - used as an example # https://bokeh.pydata.org/en/latest/docs/user_guide/interaction/callbacks.html x = [x * 0.005 for x in range(0, 200)] y = x source = ColumnDataSource(data=dict(x=x, y=y)) plot = Figure(plot_width=400, plot_height=400) plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) callback = CustomJS(args=dict(source=source), code=""" var data = source.data; var f = cb_obj.value var x = data['x'] var y = data['y'] for (var i = 0; i < x.length; i++) { y[i] = Math.pow(x[i], f) } source.change.emit(); """) slider = Slider(start=0.1, end=4, value=1, step=.1, title="power") slider.js_on_change('value', callback) layout = column(slider, plot) return json.dumps(json_item(layout, "myplot"))
def aquisition_timeseries(acquisition_id): counts = list( db.session.query( FrameModel.counts).filter_by(acquisition_id=acquisition_id).all()) plot = generate_counts_plot(counts) return json.dumps(json_item(plot, "acquisition_timeseries"))
def bokeh(): x = [x * 0.005 for x in range(0, 200)] y = x source = ColumnDataSource(data=dict(x=x, y=y)) plot = Figure(plot_width=400, plot_height=400) plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) callback = CustomJS(args=dict(source=source), code=""" var data = source.data; var f = cb_obj.value var x = data['x'] var y = data['y'] for (var i = 0; i < x.length; i++) { y[i] = Math.pow(x[i], f) } source.change.emit(); """) slider = Slider(start=0.1, end=4, value=1, step=.1, title="power") slider.js_on_change('value', callback) layout = column(slider, plot) return json.dumps(json_item(layout, "myplot"))
def givegraph(self): self.makedf() source = ColumnDataSource( data=dict(Means=self.df5.index, Freqs=self.df5.values)) if self.gen_graph == 1: p = figure(plot_width=500, plot_height=400, tools='pan, reset') p.title.text = "Dystrybucja" p.title.text_color = "Orange" p.title.text_font = "times" p.title.text_font_style = "italic" p.yaxis.minor_tick_line_color = "Yellow" p.xaxis.axis_label = "Średnie" p.yaxis.axis_label = "Częstotliwości" p.circle( x='Means', y='Freqs', source=source, size=10, color="red", alpha=0.6, ) hover = HoverTool(tooltips=[("Mean", "@Means"), ("Freq", "@Freqs")]) p.add_tools(hover) return json.dumps(json_item(p)) else: return "0"
def evaluateNode(self, result, nodeDic, nodeId, dims=None, rows=None, columns=None, summaryBy="sum", bottomTotal=False, rightTotal=False, fromRow=0, toRow=0, hideEmpty=None, rowOrder='original', columnOrder='original'): _result = result if isinstance(_result, Figure): # create layout _result.sizing_mode = 'stretch_both' elif isinstance(result, Widget): pass elif isinstance(_result, LayoutDOM): # update layout for all childrens _result.sizing_mode = 'stretch_both' for item in _result.children: if isinstance(item, LayoutDOM) and not isinstance(item, Widget): if item.sizing_mode is None and item.width_policy == "auto" and item.height_policy == "auto": item.sizing_mode = 'stretch_both' res = dict() res["result"] = "BOKEH:" + json.dumps(json_item(_result, "#bokeh-id#")) return json.dumps(res)
def get_bar_plots(self, fields): plots = [] for field in fields: d = self.get_dist(col_name=field) data = pd.Series(d).reset_index(name='value').rename(columns={'index': 'field'}) data['color'] = Category20[len(d)] # convert any int value to str categorial type data['str_field'] = list(map(str, data['field'])) p = figure(title="Distribution of {}".format(field), plot_height=500, tools="hover", toolbar_location=None, tooltips="@field:@value", x_range=data['str_field']) p.vbar(source=data, x='str_field', top='value', line_color="green" , fill_color='color' # ,legend_field='str_field' ) p.xaxis.axis_label = field p.xaxis.major_label_orientation = "vertical" p.yaxis.axis_label = "Count" # p.legend.orientation = "horizontal" # p.legend.location = "top_left" plots.append(p) return json.dumps(json_item(gridplot(plots, ncols=2, sizing_mode="fixed")))
def getScatterPlot(self): x = self.x y = self.y TOOLS = "hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out," p = figure(tools=TOOLS, plot_width=300, plot_height=150) p.scatter(x, y, fill_color='#6666ff', fill_alpha=0.3, line_color="#333399") p.line([x.min(), x.max()], [x.min(), x.max()], line_color="#666699", line_width=4, line_dash='dashed') p.toolbar.logo = None p.sizing_mode = 'scale_width' jsonified = json.dumps(json_item(p, "scatter-plot")) return jsonified
def main(event, context): try: x = [1, 2, 3, 4, 5] y = [6, 7, 8, 9, 10] plot = figure() plot.line(x, y, line_width=3) plot.circle(x, y, fill_color='white', size=10) plot_json = json.dumps(json_item(plot, 'myplot')) return { 'statusCode': 200, 'headers': { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': True, }, 'body': plot_json, } except Exception as exc: print(exc) return { 'statusCode': 400, 'headers': { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': True, }, 'body': '{"status": "fail"}', }
def plotth(): data = db.read_db() xdataTemp = [] ydataTemp = [] xdataHumidity = [] ydataHumidity = [] for i in range(0, len(data['temperature'])): xdataTemp.append(data['temperature'][i]['_id']) ydataTemp.append(data['temperature'][i]['value']) for i in range(0, len(data['humidity'])): xdataHumidity.append(data['humidity'][i]['_id']) ydataHumidity.append(data['humidity'][i]['value']) # Filter out (remove) all 'None' values from the dictionary and replace by previous value # Solution: https://stackoverflow.com/questions/35868549/fill-na-in-a-list-with-the-last-know-value-in-python for i, j in enumerate(ydataTemp): if j is None: if i == 0: ydataTemp = next(item for item in ydataTemp if item is not None) else: ydataTemp[i] = ydataTemp[i-1] for i, j in enumerate(ydataHumidity): if j is None: if i == 0: ydataHumidity = next(item for item in ydataHumidity if item is not None) else: ydataHumidity[i] = ydataHumidity[i - 1] xdataTemp = [datetime.strptime(date, "%m/%d/%Y;%H:%M:%S") for date in xdataTemp] xdataHumidity = [datetime.strptime(date, "%m/%d/%Y;%H:%M:%S") for date in xdataHumidity] plot = figure(x_axis_label='date', x_axis_type='datetime', width=600, height=600) plot.line(xdataTemp, ydataTemp, line_width=2, line_color='green') plot.line(xdataHumidity, ydataHumidity, line_width=2, line_color='blue') # return Markup(file_html(plot, CDN, "data")) return json.dumps(json_item(plot, "thplot"))
def degreeAPI(type=None, dir=None): # Not used # if file is not None: # filePath = 'api/filter/cached_plots/{}-{}-{}.json'.format(file, type, dir) # if (exists(filePath)): # with open(filePath, 'r') as json_file: # return json_file.read() # else: # with open(filePath, 'w+') as json_file: # plot = generate_selection(getFilePath(file), kind=type, dir=dir) # start = time() # item = json_item(plot) # dump(item, json_file) # print("To json {}-{}: ".format(dir, type) + str(time()-start)) # return dumps(item) # All filters use this sid = request.cookies.get(server.config['SESSION_COOKIE_NAME']) if type == 'weight': data = get_df(sid) if type == 'degree': if dir == 'in': data = get_partially_filtered_df(sid) if dir == 'out': data = get_almost_filtered_df(sid) plot = generate_selection(sid, data, kind=type, dir=dir, dataframe=True) return dumps(json_item(plot))
async def plot( *, resource_url: str = Query(..., title="Resource URL", description="URL to a netcdf resource"), get: str = Query( ..., title="Query string", description= "Receive list of parameters or get the plot, specifying the variable name", regex='^(param|plot)$'), variable: str = Query(None, title="Variable name", description="String with the NetCDF Variable name")): if get == 'param': #variables, datetimeranges = get_plottable_variables(netCDF4.Dataset(str(resource_url), mode="r")) #return {"y_axis": [i[0] for i in variables]} return get_plottable_variables(resource_url) if get == 'plot': if not variable or variable not in get_plottable_variables( resource_url)["y_axis"]: raise HTTPException(status_code=404, detail="Variable not found") data = get_data(resource_url, variable, resample=None) #json_plot = create_plot(data) json_plot = create_page(data) json_data = json_item(json_plot, target='tsplot') #json_data['test'] = "<b>BOLD</b>" return json_data if get == 'data': if not variable or variable not in get_plottable_variables( resource_url)["y_axis"]: raise HTTPException(status_code=404, detail="Variable not found") data = get_data(resource_url, variable, resample=None) return data
def Layout(width, height, xl, xr, yl, yr): hover = HoverTool( tooltips=[ # ("index", "$index"), # ("data (using $) (x,y)", "($x, $y)"), # ("data (using @) (x,y)", "(@x, @y)"), # ("canvas (x,y)", "($sx, $sy)") ("Name", "@N"), ("Occupied", "@O"), ("Capacity", "@C") ], names=["target"]) TOOLS = "reset,wheel_zoom,pan" p = figure(name="Map", title="Nanyang Technological University" + dat(), tools=TOOLS, plot_width=int(width), plot_height=int(height), toolbar_location="below", x_range=(xl, xr), y_range=(yl, yr)) # Add the lines to the map from our 'msource' ColumnDataSource -object # p.triangle('x','y',source=handdler(address,"PN"), color='brown',line_color="brown", legend_label='address') # p.triangle('x','y', source=handdler(amenity_points,"PN"), color='lightblue', legend_label='amenity_pn') # p.patches('x','y', source=handdler(amenity_polygons,"PG"), color='lightblue', legend_label='amenity_pg') # p.multi_line('x','y', source=handdler(bridges,"LS"), color='lightgrey', legend_label='bridges', line_width=1) p.patches('x', 'y', source=handdler(buildings, "PG"), color='lightgrey', legend_label='buildings') # p.patches('x','y', source=handdler(forests,"PG"), color='lightyellow', legend_label='forests') # p.patches('x','y', source=handdler(landcover,"PG"), color='lightblue', legend_label='landcover') # p.patches('x','y', source=handdler(now,"LS"), color='lightblue', legend_label='buildings') # p.multi_line('x','y', source=handdler(railways,"LS"), color='lightgrey', legend_label='railways', line_width=1) p.multi_line('x', 'y', source=handdler(roads, "LS"), color='lightgrey', legend_label='roads', line_width=1) # p.triangle('x','y', source=handdler(stations,"PN"), color='lightblue', legend_label='stations') p.patches('x', 'y', source=roomshanddler(s2_b4), color='blue', legend_label='S2 Level B3', name="target") # p.triangle('x','y', source=handdler(trees,"PN"), color='lightblue', legend_label='trees') # tunnels # p.patches('x','y', source=handdler(water_areas,"PG"), color='lightblue', legend_label='water') # water_lines p.xaxis.axis_label = "Longitude" p.yaxis.axis_label = "Latitude" p.add_tools(hover) return json.dumps(json_item(p, "myplot"))
def create_twn(): words_p, pop_p, pop_p_unique, words_np, pop_np, pop_np_unique = tw_nlp_data( ) tw_nlp = tw_nlp_create(words_p, pop_p, pop_p_unique, words_np, pop_np, pop_np_unique) return simplejson.dumps(json_item(tw_nlp, "tw_nlp"))
def plot(): p = make_plot('petal_width', 'petal_length') return json.dumps(json_item(p, "myplot"))
def plot2(): p = make_plot('sepal_width', 'sepal_length') return json.dumps(json_item(p))