def bokeh_sketch_dot_func(self): output_file('columndatasource_example.html') data=pd.read_csv("test.csv") #data.drop(["Hulu_id"],axis=1,inplace=True) print(data) p = figure() sample = data.sample(4) source = ColumnDataSource(sample) p.circle(x='TOTAL_TONS', y='AC_ATTACKING', source=source, size=10, color='green') p.title.text = 'Attacking Aircraft and Munitions Dropped' p.xaxis.axis_label = 'Tons of Munitions Dropped' p.yaxis.axis_label = 'Number of Attacking Aircraft' hover = HoverTool() hover.tooltips=[ ('Attack Date', '@MSNDATE'), ('Attacking Aircraft', '@AC_ATTACKING'), ('Tons of Munitions', '@TOTAL_TONS'), ('Type of Aircraft', '@AIRCRAFT_NAME') ] p.add_tools(hover) show(p)
def week_single_graphs(self): for day in range(7): p = figure( width = 1200,height=650,title="{0}".format(self.name_o_days[day]),x_axis_type="datetime", logo = None,tools="pan, wheel_zoom,reset", active_drag="pan")#fill week self.time_var = [self.datetime] hours_open = len(self.dem.week_pop[day])-1 for x in range(hours_open): self.datetime = self.datetime+self.one_hour self.time_var.append(self.datetime) # datetime= datetime+one_day self.datetime = self.datetime - hours_open*self.one_hour source = ColumnDataSource(dict( x=self.time_var, y=self.dem.week_pop[day], volume=self.dem.week_volume[day], density=self.dem.week_density[day], )) hover = HoverTool() hover.tooltips = [ ("(x,y)","($x,$y)"), ("volume","@volume"), ("density","@density") ] p.xaxis.formatter= self.time_format p.yaxis.axis_label = "Population" p.xaxis.axis_label = "Time" p.circle("x","y",source=source,legend="{0}".format(self.name_o_days[day]),color = self.colors[day]) p.line("x","y",source=source,color = self.colors[day]) p.tools.append(hover) show(p)
def hover_tool(): """ Return custom HoverTool with <div> <div> - champion image - champion usage count - champion average tier - champion average placement - champion average number of item </div> """ hover = HoverTool() hover.tooltips = """ <div style="background-color:rgba(0,0,0,0.1);"> <div style="border-radius: 1px; background-color:rgba(0,0,0,0.1);"> <img src=@image alt="" width="125" height="125"> </div> <div style="text-align:center; font-size:16px;"><strong>@champion_name</strong></div> <div><strong>Count: @count (@count_percent%)</strong></div> <div><strong>Avg_Tier: @average_tier</strong></div> <div><strong>Avg_Placement: @average_placement</strong></div> <div><strong>Avg_#_Item: @average_number_item</strong></div> </div> """ return hover
def save_to_html_for_account_code(new_df, filename, account_code): reset_output() output_file(filename) sample = new_df.loc[new_df['account_code'] == account_code] source = ColumnDataSource(sample) clients = source.data['client_name'].tolist() p = figure(x_range=clients) p.vbar(x='client_name', top='test_prediction', source=source, width=0.50, color='red') p.xaxis.major_label_orientation = "vertical" p.title.text = 'Bank Marketing Predictions' p.yaxis.axis_label = 'Prediction rate' hover = HoverTool() hover.tooltips = [('Client Name', '@client_name'), ('Account Code', '@account_code'), ('Age', '@age'), ('Campaign', '@campaign'), ('Pdays', '@pdays'), ('Previous', '@previous'), ('Marital status', '@marital_married'), ('Target', '@test_prediction')] p.add_tools(hover) save(p)
def create_chart_2(df): categories = sorted(df['acct_type'].unique().tolist()) grouped = df.groupby('acct_type').sum() source = ColumnDataSource(grouped) cats = source.data['acct_type'].tolist() p = figure(x_range=cats, plot_width=500) color_map = factor_cmap(field_name='acct_type', palette=Spectral5, factors=cats) p.vbar(x='acct_type', top='actual_amount', source=source, width=0.70, color=color_map) p.title.text = 'Spend by Account' p.xaxis.axis_label = 'Account' p.yaxis.axis_label = 'Actual amounts' p.xaxis.major_label_orientation = 'vertical' hover = HoverTool() hover.tooltips = [("Totals", "@actual_amount")] hover.mode = 'vline' p.add_tools(hover) return p
def generate_plot(data): # try: # data["Time:"] = [datetime.datetime.fromtimestamp(x) for x in data["Time:"]] # data['Time:'] = [x.strftime("%H:%M:%S.{} %p".format(x.microsecond % 100)) for x in data["Time:"]] # except TypeError: # pass print(data) source = ColumnDataSource(data) print(source.column_names) p = figure(x_axis_type='datetime') print(p.line(x='Time:', y='Temp Value:', source=source)) # p.line(x='Time:', y='Strain Value:', source=source) p.plot_width = 800 p.plot_height = 800 p.title.text = 'Device Readings' p.xaxis.axis_label = 'Time of Reading' p.yaxis.axis_label = 'Readings' hover = HoverTool() hover.tooltips = [ ('Time of Reading', '@{Time:}{%M:%S.%3N}'), ] hover.formatters = {"@{Time:}": "datetime"} p.add_tools(hover) # show(p) return p, source
def getSentiment(df_tws): # count sentiments from each tweet tw_pos = sum(df_tws['sentiment'] == 1) tw_neu = sum(df_tws['sentiment'] == 0) tw_neg = sum(df_tws['sentiment'] == -1) # plot results group = ['Negative', 'Neutral', 'Positive'] counts = [tw_neg, tw_neu, tw_pos] p = figure(plot_height=400, x_range=group, title='Sentiment Analysis', toolbar_location=None, tools='') p.vbar(x=group, top=counts, width=0.8) # , source=source) p.y_range.start = 0 p.xgrid.grid_line_color = None p.xaxis.axis_label = 'Hashtags' p.xaxis.major_label_orientation = 1.2 p.outline_line_color = None p.legend.location = 'top_left' p.legend.click_policy = 'hide' hover = HoverTool() hover.tooltips = [('Negative', '@tw_neg'), ('Neutral', '@tw_neu'), ('Positive', '@tw_pos')] p.add_tools(hover) return p
def plot_country_data_2019(): from bokeh.plotting import figure, output_file, ColumnDataSource from bokeh.models.tools import HoverTool from bokeh.transform import factor_cmap from bokeh.palettes import Viridis256 from bokeh.embed import components from bokeh.resources import CDN import pandas as pd dataF = pd.read_csv('CountriesPopulation_2019.csv') output_file('population_2019.html') data_source = ColumnDataSource(dataF) countries_list = list(data_source.data['Country']) fig = figure(y_range=countries_list, plot_height=700, plot_width=800, title='The Population Of 2019', x_axis_label='Population', sizing_mode='scale_width' ) fig.hbar(y='Country', right='Population', left=0, height=0.7, fill_color=factor_cmap( 'Country', factors=countries_list, palette=Viridis256[:229] ), fill_alpha=0.8, source=data_source, ) hover = HoverTool() hover.tooltips = """ <div> <h2>@Country</h2> <div><b>Population: </b>@Population</div> </div>""" fig.add_tools(hover) script, div = components(fig) cdn_js = CDN.js_files[0] cdn_css = 'https://cdn.pydata.org/bokeh/release/bokeh-1.2.0.min.css' return render_template('country_data2019_plot.html', script=script, div=div, cdn_css=cdn_css, cdn_js=cdn_js)
def bar_charts(self): output_file('munitions_by_country.html') data = pd.read_csv('test.csv') # We now need to get from the 170,000+ # records of individual missions to one record per attacking country with the total munitions dropped grouped = data.groupby('COUNTRY_FLYING_MISSION')['TOTAL_TONS', 'TONS_HE', 'TONS_IC', 'TONS_FRAG'].sum() """Pandas lets us do this in a single line of code by using the groupby dataframe method. This method accepts a column by which to group the data and one or more aggregating methods that tell Pandas how to group the data together. The output is a new dataframe. Let's take this one piece at a time. The groupby('COUNTRY_FLYING_MISSION') sets the column that we are grouping on. In other words, this says that we want the resulting dataframe to have one row per unique entry in the column COUNTRY_FLYING_MISSION. Since we don't care about aggregating all 19 columns in the dataframe, we choose just the tons of munitions columns with the indexer, ['TOTAL_TONS', 'TONS_HE', 'TONS_IC', 'TONS_FRAG']. Finally, we use the sum method to let Pandas know how to aggregate all of the different rows. Other methods also exist for aggregating, such as count, mean, max, and min.""" print(grouped) #To plot this data, let's convert to kilotons by dividing by 1000. grouped = grouped / 1000 source = ColumnDataSource(grouped) countries = source.data['COUNTRY_FLYING_MISSION'].tolist() p = figure(x_range=countries) """Now, we need to make a ColumnDataSource from our grouped data and create a figure. Since our x-axis will list the five countries (rather than numerical data) we need to tell the figure how to handle the x-axis. To do this, we create a list of countries from our source object, using source.data and the column name as key. The list of countries is then passed as the x_range to our figure constructor. Because this is a list of text data, the figure knows the x-axis is categorical and it also knows what possible values our x range can take (i.e. AUSTRALIA, GREAT BRITAIN, etc.).""" color_map = factor_cmap(field_name='COUNTRY_FLYING_MISSION', palette=Spectral5, factors=countries) p.vbar(x='COUNTRY_FLYING_MISSION', top='TOTAL_TONS', source=source, width=0.70, color=color_map) p.title.text ='Munitions Dropped by Allied Country' p.xaxis.axis_label = 'Country' p.yaxis.axis_label = 'Kilotons of Munitions' """To color our bars we use the factor_cmap helper function. This creates a special color map that matches an individual color to each category (i.e. what Bokeh calls a factor). The color map is then passed as the color argument to our vbar glyph method. For the data in our glyph method, passing a source and again referencing column names. Instead of using a y parameter, however, the vbar method takes a top parameter. A bottom parameter can equally be specified, but if left out, its default value is 0.""" hover = HoverTool() hover.tooltips = [ ("Totals", "@TONS_HE High Explosive / @TONS_IC Incendiary / @TONS_FRAG Fragmentation")] hover.mode = 'vline' """ vline and hline tell the popup to show when a vertical or horizontal line crosses a glyph. With vline set here, anytime your mouse passes through an imaginary vertical line extending from each bar, a popup will show.""" p.add_tools(hover) show(p)
def cezar(request): context = {} if request.method == "POST": selected = request.POST.get("select") filed = request.POST.get("file") uploaded1 = request.FILES['file'] contentOfFile = uploaded1.read() d = counter(contentOfFile.decode("utf-8")) sorted_d = {k: v for k, v in sorted( d.items(), key=lambda item: item[1])} v = list(sorted_d.values()) k = list(sorted_d.keys()) if selected == "az": k = list(d.keys()) source = ColumnDataSource( data=dict(x=list(d.keys()), y=list(d.values()))) elif selected == "za": k = list(d.keys())[::-1] source = ColumnDataSource( data=dict(x=list(d.keys())[::-1], y=list(d.values())[::-1])) elif selected == "asc": source = ColumnDataSource(data=dict(x=k, y=v)) elif selected == "desc": k = k[::-1] source = ColumnDataSource(data=dict(x=k[::-1], y=v[::-1])) hover = HoverTool() hover.tooltips = """ <div> <h3>@x</h3> <div><strong>Repeats: </strong>@y</div> </div> """ p = figure( x_range=k, plot_width=900, plot_height=400, title="Histogram", y_axis_label="Repeats" ) p.vbar( x='x', top='y', width=0.4, fill_alpha=0.7, source=source ) p.add_tools(hover) script, div = components(p) context["script"] = script context["div"] = div return render(request, "cryptology/cezar.html", context)
def plot(): df = pd.read_csv('test2/sent_stock_data3.csv') df['date_time'] = pd.to_datetime(df['date_time']) #df.info() part = df source = ColumnDataSource( data=dict(x=part.date_time, y=part.stock_price, z=part.avg_sentiment)) plot = figure(title="Stock price with sentiment graph", x_axis_label='Date', y_axis_label='Stock price', x_axis_type='datetime') plot.line(x='x', y='y', source=source, line_color='blue', line_width=5) sent = "neutral" for a in range(len(part.date_time)): view = CDSView(source=source, filters=[IndexFilter([a])]) if source.data['z'][a] > 0.1: plot.circle(source.data['x'][a], source.data['y'][a], source=source, view=view, fill_color='green', size=50) elif source.data['z'][a] < -0.1: plot.circle(source.data['x'][a], source.data['y'][a], source=source, view=view, fill_color='red', size=50) else: plot.circle(source.data['x'][a], source.data['y'][a], source=source, view=view, fill_color='blue', size=50) hover = HoverTool() hover.tooltips = [('Average sentiment', sent), ('Exact price', '@y')] plot.add_tools(hover) script1, div1 = components(plot) cdn_js = CDN.js_files #cdn_js[0] only need this link cdn_json = cdn_js[0] return render_template('graph.html', script1=script1, div1=div1, cdn_json=cdn_json)
def showBestAsset(dfmerged): dfsort = (dfmerged.groupby(['AssetID', 'Asset type']).mean().reset_index()) dfsort['Efficiency (liters per hour)'] = dfsort.apply( lambda x: x['Total Fuel (Liters)'] / x['Total Hours'], axis=1) print(dfsort.loc[dfsort["Efficiency (liters per hour)"].idxmax()]) print(dfsort.loc[dfsort["Efficiency (liters per hour)"].idxmin()]) print(dfsort["Asset type"].unique()) sample = dfsort.sample(1000) source = ColumnDataSource(sample) index_cmap = factor_cmap( 'Asset type', palette=['red', 'blue', 'green', 'navy', 'yellow', 'olive'], factors=sorted(dfsort['Asset type'].unique())) output_file("gg.html") p = figure() p.circle(x='Total Fuel (Liters)', y='Total Hours', source=dfsort, size=5, fill_color=index_cmap, legend='Asset type') p.title.text = 'Assets and their fuel consumption' p.xaxis.axis_label = 'Average fuel consumed over a year in Liters' p.yaxis.axis_label = 'Average time used over a year in hours' hover = HoverTool() hover.tooltips = [('Asset ID', '@AssetID'), ('Asset Type', '@{Asset type}'), ('Average fuel level', '@{Fuel Level (%)}'), ('Efficiency', '@{Efficiency (liters per hour)}')] p.add_tools(hover) p.legend.location = "top_left" div_exp00 = Div(text=""" <b>FUEL EFFICIENCY GRAPH</b> """, width=300, style={'font-size': '100%'}) div_exp01 = Div( text= """ Mileage is a key factor when it comes to analysing the performance of motor vehicles, for heavy duty vehicles the fuel consumed over time plays a similar role. The graph shows the average fuel consumption for each asset in the fleet in a year. Each sphere represents an unique asset and the slope of the graph gives the average fuel consumption per hour. This data allows the fleet manager to identify the most efficient assets in the fleet. The asset can be closely inspected by zooming in and hovering over the spheres.""", width=300) show(column(div_exp00, div_exp01, p))
def make_situation_chart(df_stats: pd.DataFrame, team_name: str, year: int) -> Figure: situation = df_stats["Situation"] diff_xg = df_stats["diff_xG"] amplitude = df_stats["diff_xG"].abs().max() + 1 amplitude = max(amplitude, 4.5) # at least 4 goals of diff so clip color_mapper = LinearColorMapper(palette=RdYlGn[11][::-1], low=-amplitude, high=amplitude) h_barchart = figure( title= f"Visualisation de la diff xG pour {team_name}, saison {year}-{year + 1}", y_range=situation.values, x_range=(-amplitude, amplitude), ) h_barchart.yaxis.ticker = CategoricalTicker() hbar_chart = h_barchart.hbar( right=diff_xg, y=situation, height=0.2, color={ "field": "right", "transform": color_mapper }, ) glyph = hbar_chart.glyph glyph.fill_alpha = 1 glyph.line_color = "black" glyph.line_width = 0.2 hover = HoverTool() hover.tooltips = [("diff xG", "@y"), ("Catégorie", "@right{0.2f}")] h_barchart.add_tools(hover) h_barchart.toolbar.logo = None h_barchart.toolbar_location = None color_bar = ColorBar(color_mapper=color_mapper, width=12) color_bar_plot = figure(height=500, width=100, toolbar_location="right", title="Diff. de xG") color_bar_plot.add_layout(color_bar, "right") color_bar_plot.toolbar.logo = None color_bar_plot.toolbar_location = None layout = row(h_barchart, color_bar_plot) return layout
def job_num_salary_plot(): category = request.form['category'] app.vars['category'] = category job_salary_num = dill.load(open('job_salary_num_1120.pkl', 'rb')) job_df = job_salary_num[job_salary_num['title'] == category] df = job_df[job_salary_num['title'] == category] df['sal'] = df['salary'].apply( lambda x: int(x.replace('$', '').replace(',', ''))) df2 = df.sort_values(by='job num', ascending=False)[:10] cities = df2.Loc.values output_file('./templates/job_top10.html', title="Top10 cities") ymin = int(df2['sal'].min()) // 1000 * 1000 ymax = int(df2['sal'].max()) // 1000 * 1050 p = figure(x_range=cities, y_range=(60000, ymax), plot_width=1200, plot_height=350, title=('Top 10 cities with most job opportunities for ' + category), toolbar_location=None, tools='') p.yaxis[0].formatter = NumeralTickFormatter(format="$0,0") p.vbar(x=dodge('Loc', -0.1, range=p.x_range), top='sal', width=0.2, source=df2, line_color='white', legend_label="Salary", color='green') y2max = (int(df2['job num'].max()) // 100) * 150 p.extra_y_ranges = {'Job Number': Range1d(start=0, end=y2max)} p.add_layout(LinearAxis(y_range_name="Job Number"), 'right') p.vbar(x=dodge('Loc', 0.1, range=p.x_range), top='job num', width=0.2, source=df2, line_color='white', legend_label="Job number", color='orange', y_range_name='Job Number') p.xgrid.grid_line_color = None p.legend.location = "top_right" p.legend.orientation = "horizontal" hover = HoverTool() hover.tooltips = [('Title', '@title'), ('Average salary', '@salary'), ('Job number', '@{job num}')] hover.mode = 'vline' p.add_tools(hover) save(p) return render_template('job_num_salary_plot.html', title=category)
def plot_quality(df): """Use bokeh to plot team strengths Keyword arguments: df -- quality dataframe with columns: - Team - attack - attacksd - attack_low - attack_high - defend - defendsd - defend_low - defend_high """ source = ColumnDataSource(df) p = figure(x_range=(-1, 1.5), y_range=(-1, 1.5)) p.add_layout( Whisker( lower="attack_low", upper="attack_high", base="defend", dimension="width", source=source, )) p.add_layout( Whisker( lower="defend_low", upper="defend_high", base="attack", dimension="height", source=source, )) p.circle(x="attack", y="defend", source=source) p.title.text = "Team strengths" p.xaxis.axis_label = "Attacking" p.yaxis.axis_label = "Defending" hover = HoverTool() hover.tooltips = [ ("Team", "@Team"), ("Attacking", "@attack"), ("Attacking sd", "@attacksd"), ("Defending", "@defend"), ("Defending sd", "@defendsd"), ] p.add_tools(hover) show(p)
def handle(self, *args, **options): df = df_ cas = df['cases'].values l = [] for i in cas: q = i.replace(",", "") q = int(q) l.append(q) df['cases'] = l source = ColumnDataSource(df) output_file('templates/graph_temp.html') country_list = source.data['name'].tolist() p = figure(y_range=country_list, plot_width=2000, plot_height=3200, title='Coronavirus Cases', x_axis_label='Cases', tools="pan,box_select,zoom_in,zoom_out,save,reset") p.hbar( y='name', right='cases', left=0, height=0.7, fill_color=factor_cmap('name', palette=Blues8, factors=country_list), fill_alpha=0.9, source=source, ) hover = HoverTool() hover.tooltips = """ <div> <h3>@name</h3> <div><strong>Cases: </strong>@cases</div> <div><strong>Deaths: </strong>@deaths</div> <div><strong>Recovered: </strong>@recovered</div> <div><strong>Tests: </strong>@tests</div> </div> """ p.add_tools(hover) script, div = components(p) save(p)
def chart(): now = datetime.datetime.strftime(datetime.datetime.today(), '%Y-%m-%d') then = datetime.datetime.strftime( datetime.datetime.today() - datetime.timedelta(days=31), '%Y-%m-%d') abbr = request.form['abbr'] if len(abbr) == 0: return render_template("index.html") abbr = abbr.upper() df = yf.download(abbr, start=then, end=now, progress=False) df = df.reset_index() df.Date = pd.to_datetime(df.Date) df = df.sort_values('Date') df.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'AdjClose', 'Volume'] source = ColumnDataSource(df) p = figure(x_axis_type='datetime', width=1000) hover = HoverTool() hover.tooltips = [ ('Open', '@Open'), ('Close', '@Close'), ('AdjClose', '@AdjClose'), ('High', '@High'), ('Low', '@Low'), ('Volume', '@Volume'), ] p.add_tools(hover) p.title.text = f'From {then} to {now}' p.line(x='Date', y='Open', source=source, color='green') p.line(x='Date', y='Close', source=source, color='blue') script, div = components(p) return render_template("dashboard.html", title='Knock My Stocks Off!', abbr=abbr, the_div=div, the_script=script)
def plot_LogsOvertime(df, col1, col2, title, x_label, y_label, tooltips=[('count', '@count')]): """return interactive line plot using bokeh""" grouped = pd.DataFrame(df.groupby([col1])[col2].sum()) grouped.reset_index(inplace=True) # set amounts by billion dollars #grouped[col2]=grouped[col2]/col_transform source = ColumnDataSource(grouped) # initialize the figure p = figure(title=title, plot_width=1000, plot_height=450, x_axis_type='datetime') # create the plot p.line(x=col1, y=col2, line_width=3, source=source) # set formating parameters p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None p.title.text_font_size = "16pt" p.title.text_color = 'MidnightBlue' p.xaxis.axis_label_text_font_size = '15pt' p.yaxis.axis_label_text_font_size = '15pt' p.yaxis.axis_label = y_label p.xaxis.axis_label = x_label p.xaxis.major_label_text_font_size = '12pt' # add interactive hover tool that shows the amount awarded hover = HoverTool() #hover.tooltips = [('count', '@count')] hover.tooltips = tooltips hover.mode = 'vline' p.add_tools(hover) #display plot show(p)
def _plot_bokeh(self, current_plot, show_legend=True): from bokeh.models.tools import HoverTool from collections import OrderedDict import bokeh.plotting as bkh value_lst = self.matrix.flatten() min_el = min(value_lst) vmax = float(max(value_lst) - min_el) color_lst = [BOKEH_CMAP[int((v - min_el) / vmax * (len(BOKEH_CMAP) - 1))] \ for v in value_lst] source = bkh.ColumnDataSource(data=dict( x=self.labels * self.matrix.shape[0], y=numpy.array([[i] * self.matrix.shape[1] for i in self.labels]).flatten(), color=color_lst, value=value_lst, )) # current_plot._below = [] current_plot.x_range = bkh.FactorRange(factors=self.labels) current_plot.y_range = bkh.FactorRange(factors=self.labels) # current_plot._left = [] # current_plot.extra_y_ranges = {"foo": bkh.FactorRange(factors=self.labels)} # current_plot.add_layout(CategoricalAxis(y_range_name="foo"), place='left') # current_plot.extra_x_ranges = {"foo": bkh.FactorRange(factors=self.labels)} # current_plot.add_layout(CategoricalAxis(x_range_name="foo"), place='top') current_plot.rect('x', 'y', 0.98, 0.98, source=source, color='color', line_color=None) current_plot.grid.grid_line_color = None current_plot.axis.axis_line_color = None current_plot.axis.major_tick_line_color = None hover = current_plot.select(dict(type=HoverTool)) if hover == []: hover = HoverTool(plot=current_plot, always_active=True) hover.tooltips = OrderedDict([('labels', '@x @y'), ('value', '@value')]) current_plot.tools.append(hover) return current_plot
def main(args=None): import argparse parser = argparse.ArgumentParser( description="Calculate TOAs from event files") parser.add_argument("file", help="Input summary CSV file", type=str) parser.add_argument("--test", action="store_true", default=False) args = parser.parse_args(args) output_file("TOAs.html") df = pd.read_csv(args.file) missions = list(set(df["mission"])) p = figure() p.circle( x="mjd", y="residual", source=df, size=10, color=factor_cmap("mission", "Category10_10", missions), legend="mission", ) p.title.text = "Residuals" p.xaxis.axis_label = "MJD" p.yaxis.axis_label = "Residual (s)" hover = HoverTool() hover.tooltips = [ ("Mission", "@mission"), ("MJD", "@mjd"), ("Instrument", "@instrument"), ("Residual", "@residual"), ("ObsID", "@obsid"), ] p.add_tools(hover) output_file("summary.html") save(p) if not args.test: show(p)
def _plot_bokeh(self, current_plot, show_legend=True): from bokeh.models.tools import HoverTool from collections import OrderedDict from bokeh.models.ranges import FactorRange import bokeh.plotting as bkh value_lst = self.matrix.flatten() min_el = min(value_lst) vmax = float(max(value_lst) - min_el) color_lst = [BOKEH_CMAP[int((v - min_el) / vmax * (len(BOKEH_CMAP) - 1))] \ for v in value_lst] source = bkh.ColumnDataSource( data=dict( x=self.labels * self.matrix.shape[0], y=numpy.array([[i] * self.matrix.shape[1] for i in self.labels]).flatten(), color=color_lst, value=value_lst, ) ) # current_plot._below = [] current_plot.x_range = FactorRange(factors=self.labels) current_plot.y_range = FactorRange(factors=self.labels) # current_plot._left = [] # current_plot.extra_y_ranges = {"foo": bkh.FactorRange(factors=self.labels)} # current_plot.add_layout(CategoricalAxis(y_range_name="foo"), place='left') # current_plot.extra_x_ranges = {"foo": bkh.FactorRange(factors=self.labels)} # current_plot.add_layout(CategoricalAxis(x_range_name="foo"), place='top') current_plot.rect('x', 'y', 0.98, 0.98, source=source, color='color', line_color=None) current_plot.grid.grid_line_color = None current_plot.axis.axis_line_color = None current_plot.axis.major_tick_line_color = None hover = current_plot.select(dict(type=HoverTool)) if not hover: hover = HoverTool(plot=current_plot) hover.tooltips = OrderedDict([ ('labels', '@x @y'), ('value', '@value') ]) current_plot.tools.append(hover) return current_plot
def plot_trend(c_name): # step-1: filter data by company # step-2: plot # c_name = 'Amazon' plot_df = df[df.company_name == c_name] ## bokeh plot source = ColumnDataSource(plot_df) p = figure(x_axis_type='datetime') p.line(x='year_month_01', y='emp_begin', source=source, legend='# of Employees (Start of month)', color=Spectral3[0], line_width=2) p.line(x='year_month_01', y='emp_end', source=source, legend='# of Employees (End of month)', color='red', line_width=2) p.title.text = 'Employee growth trend for ' + c_name p.xaxis.axis_label = 'Date' p.yaxis.axis_label = 'Number of employees on platform' hover = HoverTool() hover.tooltips = [ ('Employees at the start of month', '@emp_begin'), ('Employees at the end of month', '@emp_end'), ('Month/Year', '@year_month_01 ') ] p.add_tools(hover) return p
def emp_turn_over_plot(company, negativeAxis=False): plot_df = df[df.company_name == company] df_turn_over_plot = get_turn_over_data_by_color(plot_df) if negativeAxis: # for left employees multiply with -1 so that they appear on negative y-axis df_turn_over_plot['modified_emp'] = np.where(df_turn_over_plot.color == 'red', df_turn_over_plot.emp * -1, df_turn_over_plot.emp * 1) source = ColumnDataSource(df_turn_over_plot) p = figure(x_axis_type='datetime') if negativeAxis: p.vbar(x='year_month_01', width=5, top='modified_emp', source=source, color='color', legend='legend') else: p.vbar(x='year_month_01', width=5, top='emp', source=source, color='color', legend='legend') p.title.text = 'Employee Turn-over for ' + company p.xaxis.axis_label = 'Date' p.yaxis.axis_label = 'Number of employees left or joined' hover = HoverTool() hover.tooltips = [ ('Employees(left/joined)', '@emp'), ('Month/Year', '@year_month_01 ') ] p.add_tools(hover) return p
def plot_stacked_bar_margin(df, cols, tooltips, couv_cor): # output to static HTML file output_file("state_node_clique_covers_dashboard.html"); TOOLS = "pan,wheel_zoom,box_zoom,reset,save,box_select,lasso_select"; df_numgraph = df.groupby('num_graph_G_k')[cols].mean() df_numgraph['sum'] = df_numgraph.sum(axis=1) df_percent = df_numgraph.div(df_numgraph['sum'], axis=0) df_percent = round(df_percent,2) df_percent['sum'] = df_percent['sum'] * df_numgraph['sum']; source = ColumnDataSource(df_percent) graphs = source.data['num_graph_G_k'].tolist() p = figure(x_range=graphs, tools=TOOLS, plot_height=HEIGHT, plot_width=WIDTH) p.vbar_stack(x='num_graph_G_k', stackers=cols, source=source, legend = ['etat0', 'etat1', 'etat_1', 'etat2', 'etat3'], width=0.50, color=Spectral5) p.title.text ='etats des graphes '+ couv_cor; p.xaxis.axis_label = 'graphs' p.yaxis.axis_label = '' p.xaxis.major_label_orientation = 1 hover = HoverTool() hover.tooltips = tooltips hover.mode = 'vline' p.add_tools(hover) show(p)
# #p_world_covid.xaxis[0].ticker.desired_num_ticks =round(np.busday_count(np.datetime64(source.data['date'].min(),'D'),np.datetime64(source.data['date'].max(),'D'))/3); # prefer number of labels (divide by 7 for week) p_world_covid.xaxis.major_label_orientation = -np.pi / 3 # slant the labels dtformat = "%b-%d" p_world_covid.xaxis.formatter = formatter = DatetimeTickFormatter( # Always show the same date formatting regardless of zoom days=dtformat, months=dtformat, hours=dtformat, minutes=dtformat) # Add legend p_world_covid.legend.location = "top_left" # Add a hover tool hover = HoverTool() hover.tooltips = [ #('Type', "$name"), ('', '$name: @$name{0,0.} on @date{%a-%b-%d}'), ] # hover.mode = 'vline' hover.formatters = { '@date': 'datetime', # use 'datetime' formatter for '@date' field '$name': 'printf' # use 'printf' formatter for the name of the column } hover.renderers = glyphs p_world_covid.add_tools(hover) # # Extra formatting # for ax in p_world_covid.yaxis: # ax.axis_label_text_font_style = 'bold' # ax.axis_label_text_font_size = '16pt' # p_world_covid.title.text_font_size = '20pt' # p_world_covid.title.text_font_style = 'italic'
) styling_axis(p_DateConfirmed2) p_DateConfirmed2.hbar( y=dodge('months', -0.25, range=p_DateConfirmed2.y_range), right='confirmed', height=0.3, source=source, color='color', ) p_DateConfirmed2.xgrid.visible = False p_DateConfirmed2.ygrid.visible = False hover = HoverTool() hover.tooltips = """ <div> <h3>@months</h3> <div><strong>확진: </strong>@confirmed</div> </div> """ p_DateConfirmed2.add_tools(hover) # ======================= COVID_log finish ========================== # ======================= Work From Home ============================ df_WFH = house() df_conf1 = pd.read_csv('코로나 일별 확진자 수 전처리 후파일.csv') df_conf1 = df_conf1[df_conf1['date'] <= 20200914] WFH_date = pd.to_datetime(df_WFH['date'], format='%Y%m%d', errors='ignore')
########## source2 = ColumnDataSource(data4umap) ########## dCls = gen_data_forHover(sample) palette2 = viridis(len(sample['clsLabel'].unique())) colors2 = [palette2[int(x)] for x in sample['clsLabel']] dCls["color"] = colors2 source3 = ColumnDataSource(data=dCls) ########## hover = HoverTool() hover.tooltips = [('Label', '@Label'), ('clsLabel', '@clsLabel'), ('Metadata_Plate', '@Metadata_Plate'), ('Metadata_Well', '@Metadata_Well'), ('Metadata_Site', '@Metadata_Site'), ('ObjectNumber', '@ObjectNumber'), ('diff', '@diff'), ('meanInt', '@meanInt'), ('UpperQ', '@UpperQ'), ('MaxInt', '@MaxInt'), ('StdInt', '@StdInt')] ############### intensity box plot setup using holoviews in bokeh renderer = hv.renderer('bokeh') def boxInts(data): p1hv = hv.BoxWhisker(data, ['clsLabel'], 'meanInt', label="mean intensity per cluster").sort() p1hv.opts(show_legend=False, width=500, cmap='Set1', ylim=(-1, 40)) # p1hv.opts(show_legend=False, width=500) return p1hv
def plot_data(_country): confirmed_raw_url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data" \ "/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv " deaths_raw_url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data" \ "/csse_covid_19_time_series/time_series_19-covid-Deaths.csv " recovered_raw_url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data" \ "/csse_covid_19_time_series/time_series_19-covid-Recovered.csv " confirmed_df_raw = pd.read_csv(confirmed_raw_url) deaths_df_raw = pd.read_csv(deaths_raw_url) recovered_df_raw = pd.read_csv(recovered_raw_url) latest_date = confirmed_df_raw.columns[-1] confirmed_df_raw = confirmed_df_raw.drop(['Province/State', 'Lat', 'Long'], axis=1) total_confirmed = confirmed_df_raw.groupby( 'Country/Region', as_index=False).agg(sum).sort_values(latest_date, ascending=False) total_confirmed = pd.melt(total_confirmed, id_vars='Country/Region', var_name='Dates', value_name='Confirmed') total_confirmed['Dates'] = pd.to_datetime(total_confirmed['Dates']) deaths_df_raw = deaths_df_raw.drop(['Province/State', 'Lat', 'Long'], axis=1) total_deaths = deaths_df_raw.groupby( 'Country/Region', as_index=False).agg(sum).sort_values(latest_date, ascending=False) total_deaths = pd.melt(total_deaths, id_vars='Country/Region', var_name='Dates', value_name='Deaths') total_deaths['Dates'] = pd.to_datetime(total_deaths['Dates']) recovered_df_raw = recovered_df_raw.drop(['Province/State', 'Lat', 'Long'], axis=1) total_recovered = recovered_df_raw.groupby( 'Country/Region', as_index=False).agg(sum).sort_values(latest_date, ascending=False) total_recovered = pd.melt(total_recovered, id_vars='Country/Region', var_name='Dates', value_name='Recovered') total_recovered['Dates'] = pd.to_datetime(total_recovered['Dates']) country_names = total_recovered['Country/Region'].unique() mask_confirmed = total_confirmed['Country/Region'] == _country mask_death = total_deaths['Country/Region'] == _country mask_recovered = total_recovered['Country/Region'] == _country _confirmed = total_confirmed[mask_confirmed].reset_index() _deaths = total_deaths[mask_death].reset_index() _recovered = total_recovered[mask_recovered].reset_index() _confirmed['Deaths'] = _deaths['Deaths'] _confirmed['Recovered'] = _recovered['Recovered'] _confirmed['Active'] = _confirmed['Confirmed'] - _confirmed[ 'Deaths'] - _confirmed['Recovered'] _active = ColumnDataSource(_confirmed) _confirmed = ColumnDataSource(_confirmed) p = figure(title="All Cases", x_axis_label='Date', y_axis_label='Count', x_axis_type='datetime', plot_width=600, plot_height=400) p.line(x='Dates', y='Confirmed', source=_confirmed, color='black', line_width=3, legend="Confirmed Cases") p.line(x='Dates', y='Deaths', source=_confirmed, color='red', line_width=3, legend="Confirmed Deaths") p.line(x='Dates', y='Recovered', source=_confirmed, color='green', line_width=3, legend="Recoveries") hover = HoverTool() hover.tooltips = [('Confirmed', '@Confirmed'), ('Deaths', '@Deaths'), ('Recoveries', '@Recovered')] p.add_tools(hover) p.legend.location = 'top_left' p.toolbar.logo = None p.toolbar_location = None p1 = figure(title="Active Cases", x_axis_label='Date', y_axis_label='Active Cases', x_axis_type='datetime', plot_width=600, plot_height=400) p1.line(x='Dates', y='Active', source=_active, color='black', line_width=3) hover1 = HoverTool() hover1.tooltips = [('Active Cases', '@Active')] p1.add_tools(hover1) p1.toolbar.logo = None p1.toolbar_location = None return p, p1, country_names
'tsneY', source=filsource, alpha=0.6, size='ptcex', color='ptcol', line_color="lcol", line_width=3) txt = Text(x='tsneX', y='tsneY', text='title', text_alpha='txt_alpha', text_align='center') p1.add_glyph(filsource, txt) hover = HoverTool() hover.tooltips = [('Votes', '@n_vote'), ('Adoption', '@vote'), ('Titre', '@title')] hover.renderers = [r1] p1.add_tools(hover) tool = PointDrawTool(renderers=[r1], num_objects=2000) p1.add_tools(tool) filsource.selected.js_on_change( 'indices', CustomJS(args=dict(source=filsource, s2=s2, div=div), code=""" var inds = cb_obj.indices; var d1 = source.data; var d2 = s2.data; d2['vote'] = [] d2['n_vote'] = []
def generate_graphic(wcs_dataDF, output_base_filename, log_level): """Generate the graphics associated with this particular type of data. Parameters ========== wcs_dataDF : Pandas dataframe A subset of the input Dataframe consisting only of the WCS_COLUMNS and Aperture 2 output_base_filename : str Base name for the HMTL file generated by Bokeh. log_level : int, optional The desired level of verboseness in the log statements displayed on the screen and written to the .log file. Default value is 20, or 'info'. Returns ======= Nothing HTML file is generated and written to the current directory. """ # Set the output file immediately as advised by Bokeh. output_file(output_base_filename + '.html') # Setup the source of the data to be plotted so the axis variables can be # referenced by column name in the Pandas dataframe sourceCDS = ColumnDataSource(wcs_dataDF) num_of_datasets = len(wcs_dataDF.index) print('Number of datasets: {}'.format(num_of_datasets)) TOOLS = "box_zoom,wheel_zoom,box_select,lasso_select,reset,help" # Define a figure object # Aperture 1 p1 = figure(tools=TOOLS, toolbar_location="right") p2 = figure(tools=TOOLS, toolbar_location="right") p3 = figure(tools=TOOLS, toolbar_location="right") # Get the existing/remaining columns of the WCS_COLUMNS to know which # glyphs to generate # Figure 1 delta_crpix1 vs delta_crpix2 # Figure 2 delta_crval1 vs delta_crval2 wcs_components = [ 'del_def_wcsname', 'del_apriori_wcsname', 'del_apost_wcsname' ] wcs_type_colors = ['blue', 'green', 'purple'] wcs_type_names = ['default', 'apriori', 'aposteriori'] alt_wcs_names = [ 'alt_def_wcsname', 'alt_apriori_wcsname', 'alt_apost_wcsname' ] for i, wcs_component in enumerate(wcs_components): if wcs_component in wcs_dataDF.columns: slist = wcs_component.rsplit('_') xcol_pix = 'del_{}_crpix1'.format(slist[1]) ycol_pix = 'del_{}_crpix2'.format(slist[1]) p1.circle(x=xcol_pix, y=ycol_pix, source=sourceCDS, fill_alpha=0.5, line_alpha=0.5, size=10, color=wcs_type_colors[i], legend_label='Delta(Active-' + wcs_type_names[i].capitalize() + ')', name=alt_wcs_names[i]) xcol_val = 'del_{}_crval1'.format(slist[1]) ycol_val = 'del_{}_crval2'.format(slist[1]) p2.circle(x=xcol_val, y=ycol_val, source=sourceCDS, fill_alpha=0.5, line_alpha=0.5, size=10, color=wcs_type_colors[i], legend_label='Delta(Active-' + wcs_type_names[i].capitalize() + ')', name=alt_wcs_names[i]) xcol_val = 'del_{}_scale'.format(slist[1]) ycol_val = 'del_{}_orient'.format(slist[1]) p3.circle(x=xcol_val, y=ycol_val, source=sourceCDS, fill_alpha=0.5, line_alpha=0.5, size=10, color=wcs_type_colors[i], legend_label='Delta(Active-' + wcs_type_names[i].capitalize() + ')', name=alt_wcs_names[i]) p1.legend.click_policy = 'hide' p1.title.text = 'WCS Component Differences (Active - Alternate)' p1.xaxis.axis_label = 'Delta CRPIX1 (pixels)' p1.yaxis.axis_label = 'Delta CRPIX2 (pixels)' hover_p1 = HoverTool() # Make the name of the graphic the actual WCS # This hover tool shows how to use a variable for one of the tooltips. The glyph for the # alternate WCS data could represent one of three different options. The glyph has the "name" # parameter set to the key of the appropriate option, and the key is interpreted as hover_p1.tooltips = [("Instrument", "@Instrument"), ("Detector", "@Detector"), ("Filter", "@Filter"), ("Dataset", "@Dataset"), ("Primary WCS", "@prim_wcsname"), ("Alternate WCS", "@$name")] p1.add_tools(hover_p1) p2.legend.click_policy = 'hide' p2.title.text = 'WCS Component Differences (Active - Alternate)' p2.xaxis.axis_label = 'Delta CRVAL1 (pixels)' p2.yaxis.axis_label = 'Delta CRVAL2 (pixels)' p2.add_tools(hover_p1) p3.legend.click_policy = 'hide' p3.title.text = 'WCS Component Differences (Active - Alternate)' p3.xaxis.axis_label = 'Delta Scale (pixels/arcseconds)' p3.yaxis.axis_label = 'Delta Orientation (degrees)' p3.add_tools(hover_p1) # Create the the HTML output, but do not display at this time grid = gridplot([[p1, p2], [p3, None]], plot_width=500, plot_height=500) show(grid) log.info( "WCS_graphics. Output HTML graphic file {} has been written.\n".format( output_base_filename + ".html"))
kind = file.stem.split("_")[0] if kind not in accuracies: accuracies[kind] = pd.DataFrame(dtype=float, columns=["Accuracy"]) if kind == "nodes": ind = int(file.stem.split(kind)[1].split("_")[1]) else: ind = file.stem.split(kind)[1].split("_")[1] accuracies[kind].loc[ind] = file.read(index_col=0)["accuracy"].iloc[-1] figures = [] for kind in accuracies: accuracies[kind].sort_index(inplace=True) outfile = output_file((Path("outputs") / kind).with_suffix(".html")) source = ColumnDataSource(accuracies[kind]) p = figure() p.circle(x='index', y='Accuracy', source=source, size=10, color='green') p.title.text = kind p.xaxis.axis_label = kind p.yaxis.axis_label = "Accuracy" hover = HoverTool() hover.tooltips = [ (kind, '@index'), ('Accuracy', '@Accuracy'), ] p.add_tools(hover) figures.append(p) show(row(figures))