def data_for_single_day(): df = pd.read_csv('data.csv') g1 = df.sort_values(by='Report_datetime', ascending=False).head(1) data = g1.to_dict(orient='list') dates = g1['Report_datetime'].tolist() output_file("dodged_bars1.html") source = ColumnDataSource(data=data) p1 = figure(x_range=dates, y_range=(0, g1[['fail', 'Pass']].values.max() + 3), plot_height=250, title="Latest execution data", toolbar_location=None, tools="") p1.vbar(x=dodge('Report_datetime', -0.25, range=p1.x_range), top='fail', width=0.4, source=source, color="#d53e4f", legend=value("fail")) p1.vbar(x=dodge('Report_datetime', 0.25, range=p1.x_range), top='Pass', width=0.4, source=source, color="#99d594", legend=value("Pass")) p1.x_range.range_padding = 0.1 p1.xgrid.grid_line_color = None p1.legend.location = "top_left" p1.legend.orientation = "horizontal" show(p1)
def plot_literacy_rate(source, districts): lit_rate = figure(x_range=districts, y_range=(0, 100), plot_height=250, title="Literacy rate", tools='save, box_zoom, wheel_zoom,reset') m = lit_rate.vbar(x=dodge('District', -0.25, range=lit_rate.x_range), top='Literacy_Rate_Male', width=0.2, source=source, color="#718dbf") f = lit_rate.vbar(x=dodge('District', 0.0, range=lit_rate.x_range), top='Literacy_Rate_Female', width=0.2, source=source, color="#e84d60") #p.x_range.range_padding = 0.1 lit_rate.xgrid.grid_line_color = None lit_rate.legend.location = "top_left" lit_rate.xaxis.major_label_orientation = 1.2 lit_rate.legend.orientation = "horizontal" legend = Legend(items=[('Male', [m]), ('Female', [f])], location=(0, 30)) legend.click_policy = "hide" lit_rate.add_layout(legend, 'right') return lit_rate
def _init_imp_plot(self): p = figure(plot_width=600, plot_height=200, x_range=CHAN_LIST[0:self.n_chan], y_range=[str(1)], toolbar_location=None) p.circle(x='channel', y="row", radius=.3, source=self.imp_source, fill_alpha=0.6, color="color", line_color='color', line_width=2) text_props = {"source": self.imp_source, "text_align": "center", "text_color": "black", "text_baseline": "middle", "text_font": "helvetica", "text_font_style": "bold"} x = dodge("channel", -0.1, range=p.x_range) r = p.text(x=x, y=dodge('row', -.4, range=p.y_range), text="impedance", **text_props) r.glyph.text_font_size = "10pt" r = p.text(x=x, y=dodge('row', -.3, range=p.y_range), text="channel", **text_props) r.glyph.text_font_size = "12pt" p.outline_line_color = None p.grid.grid_line_color = None p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.axis.major_label_standoff = 0 p.axis.visible = False return p
def histogram_weekdays(filename, metrics): bkh.reset_output() bkh.output_file(filename, title=filename) weekdays = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] fig = bkh.figure(x_range=weekdays, title='Message distribution over weekdays', width=720, height=480) fig.vbar(x=dodge('index', 0.35, range=fig.x_range), top='frequency', width=0.3, source=metrics['A']['frame_weekdays'], color=colors[0], legend=metrics['A']['name']) fig.vbar(x=dodge('index', 0.65, range=fig.x_range), top='frequency', width=0.3, source=metrics['B']['frame_weekdays'], color=colors[1], legend=metrics['B']['name']) fig.xaxis.axis_label = 'Weekday' fig.yaxis.axis_label = 'Message count' bkh.show(fig) return
def make_plot(): """Bokeh bar chart pulling data from database, grouped by ethnicity and course """ ethnicity = ['British', 'French', 'Medit', 'Indian', 'M East', 'Asian', 'Afr', 'Mex', 'Other'] course = ['Starter', 'Main', 'Desert'] data = {'ethnicity' : ethnicity, 'Starter' : count_course('Starter'), 'Main' : count_course('Main'), 'Desert' : count_course('Desert')} source = ColumnDataSource(data=data) p = figure(x_range=ethnicity, y_range=(0, 10), plot_height=350, title="Recipe counts by nationality", toolbar_location=None, tools="", background_fill_alpha=0.6, sizing_mode="scale_both") p.vbar(x=dodge('ethnicity', -0.25, range=p.x_range), top='Starter', width=0.3, source=source, color="#84f02e", legend=value("Starter")) p.vbar(x=dodge('ethnicity', 0.0, range=p.x_range), top='Main', width=0.3, source=source, color="#37d26b", legend=value("Main")) p.vbar(x=dodge('ethnicity', 0.25, range=p.x_range), top='Desert', width=0.3, source=source, color="#e2f50c", legend=value("Desert")) p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.legend.location = "top_left" p.legend.orientation = "horizontal" p.border_fill_color = "#d7e0d6" script, div = components(p) return script, div
def make_race_plot(source): p = figure(x_range=races, y_range=(0, 1), plot_height=250, title="Coronavirus cases and deaths percentage of each races in California", toolbar_location=None) #, tools="hover", tooltips="$name: @$name") p.vbar(x=dodge('races', -0.25, range=p.x_range), top='confirmed', width=0.2, source=source, color="blue", legend_label="confirmed percentage") p.vbar(x=dodge('races', 0.0, range=p.x_range), top='death', width=0.2, source=source, color="red", legend_label="death percentage") p.vbar(x=dodge('races', 0.25, range=p.x_range), top='population', width=0.2, source=source, color="orange", legend_label="population percentage") p.add_tools(HoverTool( tooltips=[ ("race", "@races"), ("confirmed", "@confirmed{0,0.000}"+"%"), ("death", "@death{0,0.000}"+"%"), ("population", "@population{0,0.000}"+"%"), ] )) p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.legend.location = "top_right" p.legend.orientation = "horizontal" return p
def get_data(self, element, ranges, style): style = self.style[self.cyclic_index] if 'angle' in style and isinstance(style['angle'], (int, float)): style['angle'] = np.deg2rad(style.get('angle', 0)) dims = element.dimensions() coords = (1, 0) if self.invert_axes else (0, 1) xdim, ydim, tdim = (dimension_sanitizer(dims[i].name) for i in coords+(2,)) mapping = dict(x=xdim, y=ydim, text=tdim) data = {d: element.dimension_values(d) for d in (xdim, ydim)} if self.xoffset is not None: mapping['x'] = dodge(xdim, self.xoffset) if self.yoffset is not None: mapping['y'] = dodge(ydim, self.yoffset) data[tdim] = [dims[2].pprint_value(v) for v in element.dimension_values(2)] self._categorize_data(data, (xdim, ydim), element.dimensions()) cdim = element.get_dimension(self.color_index) if cdim is None: return data, mapping, style cdata, cmapping = self._get_color_data(element, ranges, style, name='text_color') if dims[2] is cdim and cdata: # If color dim is same as text dim, rename color column data['text_color'] = cdata[tdim] mapping['text_color'] = dict(cmapping['text_color'], field='text_color') else: data.update(cdata) mapping.update(cmapping) return data, mapping, style
def data_group_by_date(): df = pd.read_csv('data.csv') g1 = df.groupby(['Report_datetime']).sum() g1 = df.groupby('Report_datetime', as_index=False).sum() data = g1.to_dict(orient='list') dates = g1['Report_datetime'].tolist() output_file("dodged_bars.html") source = ColumnDataSource(data=data) p = figure(x_range=dates, y_range=(0, g1[['fail', 'Pass']].values.max() + 3), plot_height=250, title="Day wise execution data", toolbar_location=None, tools="") p.vbar(x=dodge('Report_datetime', -0.25, range=p.x_range), top='fail', width=0.4, source=source, color="#fc8d59", legend=value("fail")) p.vbar(x=dodge('Report_datetime', 0.25, range=p.x_range), top='Pass', width=0.4, source=source, color="#718dbf", legend=value("Pass")) p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.legend.location = "top_left" p.legend.orientation = "horizontal" show(p)
def total_6t(self, match): self.cds_r = bk_models.ColumnDataSource(self.df_new_6t("red", match)) all_teams = list(pd.unique(self.data.schedule.team.sort_values())) self.cds_b = bk_models.ColumnDataSource(self.df_new_6t("blue", match)) r_teams = self.cds_r.column_names[1:4] b_teams = self.cds_b.column_names[1:4] tasks = self.cds_r.data['task'] plt_name = "Six Team Power Cells Placed: Match " + match self.plt_pc = bk_plotting.figure(title=plt_name, x_range=tasks, plot_width=700, plot_height=300, toolbar_location=None, tools="hover", tooltips="$name- @task: @$name") self.plt_pc.vbar_stack(r_teams, x=bk_transform.dodge('task', -0.17, range=self.plt_pc.x_range), width=0.3, source=self.cds_r, legend_label=[" " + x for x in r_teams], color=bk_palettes.Reds3) self.plt_pc.vbar_stack(b_teams, x=bk_transform.dodge('task', 0.17, range=self.plt_pc.x_range), width=0.3, source=self.cds_b, color=bk_palettes.Blues3, legend_label=[" " + x for x in b_teams]) return self.plt_pc
def draw_year_AQI(df): df['date_ym'] = df['date'].apply(lambda x: x.strftime('%Y-%m')) df_month = df.groupby(by='date_ym').mean().reset_index() df_month['month'] = df_month['date_ym'].apply(lambda x: x.split('-')[-1]) df_month['year'] = df_month['date_ym'].apply(lambda x: x.split('-')[0]) df_2017 = df_month[df_month['year']=='2017'][['month', '北京']] df_2018 = df_month[df_month['year']=='2018'][['month', '北京']] df_2019 = df_month[df_month['year']=='2019'][['month', '北京']] source_2017 = ColumnDataSource(df_2017) source_2018 = ColumnDataSource(df_2018) source_2019 = ColumnDataSource(df_2019) p = figure(x_range=list(df_2017['month']), title="2017-2019年北京AQI对比", plot_width=1150, plot_height=400) p.vbar(x=dodge('month', -0.25, range=p.x_range), top='北京', width=0.2, color="#c9d9d3", legend_label="2017", source=source_2017) p.vbar(x=dodge('month', 0, range=p.x_range), top='北京', width=0.2, color="#718dbf", legend_label="2018", source=source_2018) p.vbar(x=dodge('month', 0.25, range=p.x_range), top='北京', width=0.2, color="#e84d60", legend_label="2019", source=source_2019) p.xgrid.grid_line_color = None p.y_range.start = 0 p.add_tools(HoverTool(tooltips=[("时间", "@month"), ("AQI", "@{北京}")])) return p
def _create_plot() -> (Figure, ColumnDataSource): """Utility function for creating and styling the bar plot.""" global source, aspects, stats pos_counts, neg_counts = ([ stats.loc[(asp, pol, False), "Quantity"] for asp in aspects ] for pol in POLARITIES) np.seterr(divide="ignore") source = ColumnDataSource( data={ "aspects": aspects, "POS": pos_counts, "NEG": neg_counts, "log-POS": np.log2(pos_counts), "log-NEG": np.log2(neg_counts), }) np.seterr(divide="warn") p = figure( plot_height=145, sizing_mode="scale_width", x_range=aspects, toolbar_location="right", tools="save, tap", ) rs = [ p.vbar( x=dodge("aspects", -0.207, range=p.x_range), top="log-POS", width=0.4, source=source, color="limegreen", legend=value("POS"), name="POS", ), p.vbar( x=dodge("aspects", 0.207, range=p.x_range), top="log-NEG", width=0.4, source=source, color="orangered", legend=value("NEG"), name="NEG", ), ] for r in rs: p.add_tools( HoverTool(tooltips=[("Aspect", "@aspects"), (r.name, "@" + r.name)], renderers=[r])) p.add_layout( Title(text=" " * 7 + "Sentiment Count (log scale)", align="left", text_font_size="23px"), "left", ) p.yaxis.ticker = [] p.y_range.start = 0 p.xgrid.grid_line_color = None p.xaxis.major_label_text_font_size = "20pt" p.legend.label_text_font_size = "20pt" return p, source
def makeGroupBar(src): groups = trips_df.trip_purpose.drop_duplicates().values.tolist() p = figure(x_range=FactorRange(*groups), plot_width=column_width, plot_height=bar_height, tools="hover", toolbar_location=None) p.vbar(x=dodge('Group', -0.25, range=p.x_range), top='Observed', width=0.25, source=src, color=survey_color, legend=value("Observed")) p.vbar(x=dodge('Group', 0, range=p.x_range), top='Model', width=0.25, source=src, color=cmap_color, legend=value("Model")) p.select_one(HoverTool).tooltips = [('Observed - Trip', "@Observed{0,}"), ('Model - Trip', "@Model{0,}")] # Styling p = style(p) p.legend.click_policy = "hide" return p
def Hbarchart(src): source = src #Plot figure p = figure(y_range=source.data['town'], x_range=(0, getmaxprice+50000), plot_height=800, plot_width=800, title="Barchart of Average Median Resale Price for Selected Year 1 vs Selected Year 2", toolbar_location=None, tools="") p.hbar(y=dodge('town', -0.15, range=p.y_range), right=src.column_names[2] , height=0.2, source=source, color="#00008b", legend='name_year1') p.hbar(y=dodge('town', 0.15, range=p.y_range), right=src.column_names[3] , height=0.2, source=source, color="#87cefa", legend='name_year2') # Hover tool with hline mode hover = HoverTool(tooltips=[('Town', '@town'), ('Median1', '@year_1'), ('Median2', '@year_2'), ('% Change', '@percent_change')], mode='hline') # display a tooltip whenever the cursor is horizontally in line with a glyph p.add_tools(hover) p.y_range.range_padding = 0.1 p.ygrid.grid_line_color = None p.yaxis.axis_label = 'Towns' p.xaxis.axis_label = 'Average Median Prices' p.legend.location = "top_right" p.legend.orientation = "vertical" return (p)
def make_transit_chart(src, groups): p = figure(x_range=FactorRange(*groups), plot_width=column_width, plot_height=bar_height, tools="hover", toolbar_location=None) p.vbar(x=dodge('Group', -0.25, range=p.x_range), top='Observed', width=0.25, source=src, color=survey_color, legend=value("Observed")) p.vbar(x=dodge('Group', 0, range=p.x_range), top='Model', width=0.25, source=src, color=cmap_color, legend=value("Model")) p.select_one(HoverTool).tooltips = [ ('Observed - Transit Trip', "@Observed{0.0}%"), ('Model - Transit Trip', "@Model{0.0}%") ] # Styling p.yaxis.formatter = NumeralTickFormatter(format='0%') p.legend.click_policy = "hide" return p
def draw_bar(confirm, healRate, name): print('-- -- ' * 10, 'drawing picture of bar v1', '-- -- ' * 10) '''解决中文显示的问题''' plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False '''输出文件''' output_file('2019-nCoV各国确诊和治愈率对比1.html') yr = ['confirm', 'healRate'] data = {'country': name, 'confirm': confirm, 'healRate': healRate} source = ColumnDataSource(data=data) p = figure(x_range=name, y_range=(0, 90), plot_height=500, title='2019-nCoV各国确诊和治愈率对比1', toolbar_location=None, tools='') p.vbar(x=dodge('country', 0.0, range=p.x_range), top='confirm', width=0.2, source=source, color='#c9d9d3', legend_label='confirm') p.vbar(x=dodge('country', 0.25, range=p.x_range), top='healRate', width=0.2, source=source, color='#718dbf', legend_label='healRate') p.x_range.range_padding =0.1 p.xgrid.grid_line_color = None p.legend.location = "top_left" p.legend.orientation = "horizontal" show(p)
def make_plot(src): p = figure(x_range=list_of_params, plot_height=450, toolbar_location="right", title="Comparison of the Performance of Websites", x_axis_label = 'Performance Metric name', y_axis_label = 'Performance Metrics Value') p.vbar(x=dodge('params',-0.15,range=p.x_range), top = 'Standard', width=0.65, source=src, color = "#41b6c4", muted_color="#41b6c4", muted_alpha=0.2, fill_alpha = 0.7, hover_fill_color = 'navy', hover_fill_alpha = 1.0, legend=value("Standard")) p.vbar(x=dodge('params',0.15,range=p.x_range), top = 'input', width=0.5, source=src, color = "#084594", muted_color="#084594", muted_alpha=0.2,fill_alpha = 0.7, hover_fill_color = 'navy', hover_fill_alpha = 1.0, legend=value("input site")) # hover = HoverTool(tooltips=[('Parameter','@name'), # # ('Website','@w_name'), # # ('Proportion','@p_proportion') # ], # mode='vline') p.legend.click_policy="mute" hover = HoverTool(tooltips=[('Percentage','@y_axis_label'), #('Distribution', '@src'), #('Density', '@ys'), ], line_policy = 'next') p.add_tools(hover) p = style(p) return p
def _init_imp_plot(self): plot = figure(plot_width=600, plot_height=200, x_range=self.chan_key_list[0:self.n_chan], y_range=[str(1)], toolbar_location=None, sizing_mode="scale_width") plot.circle(x='channel', y="row", size=50, source=self.imp_source, fill_alpha=0.6, color="color", line_color='color', line_width=2) text_props = {"source": self.imp_source, "text_align": "center", "text_color": "white", "text_baseline": "middle", "text_font": "helvetica", "text_font_style": "bold"} x = dodge("channel", -0.1, range=plot.x_range) plot.text(x=x, y=dodge('row', -.35, range=plot.y_range), text="impedance", **text_props).glyph.text_font_size = "10pt" plot.text(x=x, y=dodge('row', -.25, range=plot.y_range), text="channel", **text_props).glyph.text_font_size = "12pt" plot.outline_line_color = None plot.grid.grid_line_color = None plot.axis.axis_line_color = None plot.axis.major_tick_line_color = None plot.axis.major_label_standoff = 0 plot.axis.visible = False return plot
def histogram_hourofday(filename, metrics, key, title_str, ylabel): bkh.reset_output() bkh.output_file(filename, title=filename) hours = [ '00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00' ] fig = bkh.figure(x_range=hours, title=title_str, width=1280, height=480) fig.vbar(x=dodge('index', 0.35, range=fig.x_range), top='frequency', width=0.3, source=metrics['A'][key], color=colors[0], legend=metrics['A']['name']) fig.vbar(x=dodge('index', 0.65, range=fig.x_range), top='frequency', width=0.3, source=metrics['B'][key], color=colors[1], legend=metrics['B']['name']) fig.xaxis.axis_label = 'Time' fig.yaxis.axis_label = ylabel bkh.show(fig) return
def plot_figure(res, male_res, female_res): """ Plot a line plot and a box plot in each tab :param res: a dictionary with mean gender coefficient for each bin :param male_res: a dictionary with mean male subject score for each bin :param female_res: a dictionary with mean female subject score for each bin :return: a grid plot """ x_list = list(res.keys()) y_list = list(res.values()) data = {'x': x_list, 'overall_avg': y_list, 'female_avg': list(female_res.values()), 'male_avg': list(male_res.values()) } source1 = ColumnDataSource(data=data) tooltips1 = [('Gender test coeff', '@overall_avg')] p1_line = figure(x_range=x_list, plot_height=500, tooltips=tooltips1, title='Performance between male and female' + 'students for each country') p1_line.line(x_list, y_list, line_width=2) p1_line.circle(x='x', y='overall_avg', fill_color="blue", size=8, source=source1) tooltips2 = [('Female average score', '@female_avg'), ('Male average score', '@male_avg')] p1_bar = figure(x_range=x_list, plot_height=500, tooltips=tooltips2, title='Performance male and female students' + 'for each country') p1_bar.vbar(x=dodge('x', -0.15, range=p1_line.x_range), top='female_avg', source=source1, color='#718dbf', legend='female average score', width=0.3) p1_bar.vbar(x=dodge('x', 0.15, range=p1_line.x_range), top='male_avg', source=source1, color='#e84d60', legend='male average score', width=0.3) # change just some things about the y-axes p1_line.yaxis.axis_label = "Percentage (%)" p1_line.yaxis.major_label_text_color = "black" p1_line.yaxis.major_label_orientation = "vertical" p1_bar.yaxis.axis_label = "Score" p1_bar.yaxis.major_label_text_color = "black" p1_bar.yaxis.major_label_orientation = "vertical" return gridplot([[p1_bar, p1_line]])
def plot_bokeh(L1, L2, name1, name2): bokeh.plotting.reset_output #clear the plot from last times name1 = name1.lower() #location 1 name2 = name2.lower() #location 2 #compute the chart range m = max(L1 + L2) mm = min(L1 + L2 + [0]) m = math.ceil(m) + 1 mm = math.floor(mm) - 3 #labels for bars and legend env_factors = ['commute time', 'population density', 'safety'] locations = [name1, name2] data = { 'env_factors': env_factors, name1: L1, name2: L2 } #data dictionary for bokeh plot #make the plot Future: Use seaborn. This is more complicated than I like. source = ColumnDataSource(data=data) p = figure(x_range=env_factors, y_range=(mm, m), plot_height=350, plot_width=800, toolbar_location=None, tools="") p.vbar(x=dodge('env_factors', -0.25, range=p.x_range), top=name1, width=0.2, source=source, color="#469e34", legend=value(name1)) p.vbar(x=dodge('env_factors', 0.0, range=p.x_range), top=name2, width=0.2, source=source, color="#e37d59", legend=value(name2)) hline = Span(location=0, dimension='width', line_color='black', line_width=1) p.renderers.extend([hline]) p.x_range.range_padding = 0.1 p.legend.location = "bottom_right" p.legend.orientation = "vertical" p.legend.label_text_font_size = "20pt" p.xaxis.major_label_text_font_size = "15pt" p.background_fill_color = None p.border_fill_color = None return p
def cases_gender_and_age(): covid_age_gender = 'https://www.skane.se/globalassets/lagesbild-covid-19-i-skane/sjukdomsfall-per-alder-kon.xlsx' cag = pd.read_excel(covid_age_gender, sheet_name='Antal', usecols=['Unnamed: 0', 'Män', 'Kvinnor']) cag.rename(columns={'Unnamed: 0': 'Ålder'}, inplace=True) cag = cag.dropna(subset=['Ålder']) cag['Ålder'] = cag['Ålder'].replace({'90 år eller äldre': '90 >'}) cag = cag.replace({',': '.'}) ages = cag['Ålder'].tolist() men = cag['Män'].tolist() men = [int(i) for i in men] women = cag['Kvinnor'].tolist() women = [int(i) for i in women] data = { 'ages': ages, 'men': men, 'women': women, } source = ColumnDataSource(data=data) tooltips = [ ("Ålder", "@ages"), ("Antal Män", "@men"), ("Antal Kvinnor", "@women"), ] p = figure(x_range=ages, plot_height=250, plot_width=670, title="Sjukdomsfall per ålder och kön. Uppdateras varje onsdag", toolbar_location=None, tooltips=tooltips, tools="") p.vbar(x=dodge('ages', -0.15, range=p.x_range), top='men', width=0.3, source=source, color="#abb7ed", legend_label="Antal Män") p.vbar(x=dodge('ages', 0.15, range=p.x_range), top='women', width=0.3, source=source, color="#5069c8", legend_label="Antal Kvinnor") p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.legend.location = "top_left" p.legend.orientation = "vertical" return p
def dataChart(): global data listData = data ho = list(map(str, listData['roomNo'])) Legacy_1 = list(map(str, listData['firstMethod'])) Legacy_2 = list(map(str, listData['secondMethod'])) Proposed = list(map(str, listData['proposed'])) ElectroFee = list(map(str, listData['electroFee'])) chartData = { 'ho': ho, 'Legacy_1': Legacy_1, 'Legacy_2': Legacy_2, 'Proposed': Proposed, 'ElectroFee': ElectroFee, } source = ColumnDataSource(chartData) p = figure(x_range=ho, y_range=(0, 4000), plot_height=350, title="Crossroad Apartment", toolbar_location="below", tools=tools) p.vbar(x=dodge('ho', -0.25, range=p.x_range), top='Legacy_1', width=0.2, source=source, color="#c9d9d3", legend=value("Legacy_1")) p.vbar(x=dodge('ho', 0.0, range=p.x_range), top='Legacy_2', width=0.2, source=source, color="#718dbf", legend=value("Legacy_2")) p.vbar(x=dodge('ho', 0.25, range=p.x_range), top='Proposed', width=0.2, source=source, color="#e84d60", legend=value("Proposed")) p.line(x=ho, y=ElectroFee, color="red", line_width=2.5) p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.legend.location = "top_left" p.legend.orientation = "horizontal" p.xaxis.axis_label = 'House' p.yaxis.axis_label = 'Fee Charged($)' return p
def make_group_bar(df): groups = df.index.values.tolist() census = df['Census'].values.tolist() survey = df['Survey'].values.tolist() model = df['Model'].values.tolist() data = { 'Group': groups, 'Census': census, 'Survey': survey, 'Model': model } src = ColumnDataSource(data=data) TOOLS = "hover" p = figure(x_range=FactorRange(*groups), title="Figure 1 - Auto Ownership Distribution", plot_width=column_width, plot_height=bar_height, tools="hover") p.vbar(x=dodge('Group', -0.25, range=p.x_range), top='Census', width=0.25, source=src, color=census_color, legend=value("Census")) p.vbar(x=dodge('Group', 0, range=p.x_range), top='Survey', width=0.25, source=src, color=survey_color, legend=value("Survey")) p.vbar(x=dodge('Group', 0.25, range=p.x_range), top='Model', width=0.25, source=src, color=cmap_color, legend=value("Model")) p.select_one(HoverTool).tooltips = [ ('Census - Household Total', "@Census{0,}"), ('Survey - Household Total', "@Survey{0,}"), ('Model - Household Total', "@Model{0,}") ] # Styling p = bar_style(p) p.legend.click_policy = "hide" return p
def oneteam_plot(team, num_matches=12): measures = oneteam_df(team) matches = measures.match.unique() t1plot = plt.figure(x_range=matches, title="One Team Graph: " + team, plot_height=350, plot_width=800, toolbar_location='left', tools="hover", tooltips="$name: @$name") # Hatch panels hatch_tasks = [ 'getHatch', 'csHatch', 'rocketHatch1', 'rocketHatch2', 'rocketHatch3' ] hcds_all = get_cds_averages(measures, hatch_tasks) hatch_r = t1plot.vbar_stack(hatch_tasks, x=btransform.dodge('match', -.14, range=t1plot.x_range), width=0.25, source=hcds_all, color=bpalettes.BuPu5) # Cargo cargo_tasks = [ 'getCargo', 'csCargo', 'rocketCargo1', 'rocketCargo2', 'rocketCargo3' ] ccds_all = get_cds_averages(measures, cargo_tasks) cargo_r = t1plot.vbar_stack(cargo_tasks, x=btransform.dodge('match', .14, range=t1plot.x_range), width=0.25, source=ccds_all, color=bpalettes.Oranges5) # Climb climb_tasks = ['climb1', 'climb2', 'climb3'] cl_cds = shape_climb_data(team) climb_r = t1plot.vbar_stack(climb_tasks, x=btransform.dodge('match', .41, range=t1plot.x_range), width=0.25, source=cl_cds, color=bpalettes.Viridis3) hatch_items = [(x, [hatch_r[hatch_tasks.index(x)]]) for x in hatch_tasks] cargo_items = [(x, [cargo_r[cargo_tasks.index(x)]]) for x in cargo_tasks] climb_items = [(x, [climb_r[climb_tasks.index(x)]]) for x in climb_tasks] legend = bmodels.Legend(items=hatch_items + cargo_items + climb_items, location=(0, 0)) t1plot.add_layout(legend, 'right') return t1plot
def plt_bar(hist_tabel, lbl_list, ylabel, xlabel, filename, wigth, xl, yl): w = 0.2 output_file(filename) palette = ["#c9d9d3", "#718dbf", "#e84d60"] od = cl.OrderedDict(sorted(hist_tabel['m'].items())) el = cl.OrderedDict(sorted(hist_tabel['m_el'].items())) ll = cl.OrderedDict(sorted(hist_tabel['m_ll'].items())) odl = [od[l] if l in od else 0 for l in sorted(lbl_list)] ell = [el[l] if l in el else 0 for l in sorted(lbl_list)] lll = [ll[l] if l in ll else 0 for l in sorted(lbl_list)] num = [str(s) for s in sorted(lbl_list)] d = {'num': num, 'Entity + Literal': odl, 'Entity': ell, 'Literal': lll} l = max(odl + ell + lll) p = figure(x_range=num, y_range=(0, l + (l / 4)), plot_height=350, plot_width=wigth, toolbar_location=None, tools="", x_axis_label=xl, y_axis_label=yl) p.vbar(x=dodge('num', -0.25, range=p.x_range), top='Entity + Literal', width=0.1, source=d, color="#c9d9d3", legend=value("Entity + Literal")) p.vbar(x=dodge('num', 0.0, range=p.x_range), top='Entity', width=0.1, source=d, color="#718dbf", legend=value("Entity")) p.vbar(x=dodge('num', 0.25, range=p.x_range), top='Literal', width=0.1, source=d, color="#e84d60", legend=value("Literal")) #p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.legend.orientation = "horizontal" p.legend.location = "top_left" save(p)
def create_plot(mode): """ create glyphs, text and arrows and insert them into the figures :param is_previous: is the customized or ideal tree being created? :return: plot p and the arrow data source """ title = "Karar Ağacı " + ("(Algoritmanın Seçtiği Kök Nitelikli Hali)" if mode == "customized" else "(Seçtiğiniz Kök Nitelikli Hali)") + ("\t\t\t\tTahmin Başarısı (%): " + str(round(acc * 100, 1)) if acc else "") hover = HoverTool(names=["circles", "rectangles"]) wheel = WheelZoomTool() p = figure(title=title, toolbar_location="below", tools=[hover, wheel, ResetTool(), PanTool()], x_range=groups, y_range=list(periods), tooltips=TOOLTIPS) p.axis.visible = False arrow_data_source, label = draw_arrow(data_source.data, p) p.toolbar.active_scroll = wheel p.add_layout(label) circles = p.circle("y", "x", radius=circle_radius, radius_units='screen', source=data_source, name="circles", legend="attribute_type", color=factor_cmap('attribute_type', palette=list(get_all_colors()), factors=Instance().attr_list)) rectangles = p.rect("y", "x", rect_width, rect_height, source=data_source, name="rectangles", legend="attribute_type", color=factor_cmap('attribute_type', palette=list(get_all_colors()), factors=Instance().attr_list)) p.select(name="rectangles").visible = False # Drawing on the rectangles p.text(x="nonLeafNodes_y", y=dodge("nonLeafNodes_x", 0, range=p.x_range), name="detailed_text", text="nonLeafNodes_stat", **text_props, text_font_size="7pt") p.text(x="y", y=dodge("x", 0.3, range=p.x_range), name="detailed_text", text="attribute_type", **text_props, text_font_size="8pt", text_font_style="bold") p.text(x="y", y=dodge("x", -0.3, range=p.x_range), name="detailed_text", text="instances", **text_props, text_font_size="8pt") p.text(x="leafNodes_y", y="leafNodes_x", name="detailed_text", text="decision", **text_props, text_font_size="8pt") p.select(name="detailed_text").visible = False p.text(x="leafNodes_y", text_color="orange", y=dodge("leafNodes_x", -0.4), name="decision_text", text="decision", **text_props, text_font_size="8pt") # Final settings p.outline_line_color = "white" p.grid.grid_line_color = None p.axis.axis_line_color = None p.axis.major_tick_line_color = None p.axis.major_label_standoff = 0 p.legend.orientation = "vertical" p.legend.location = "top_right" return p, arrow_data_source, circles, rectangles
def create_chart(): Color_Palette = YlOrRd[8] hour = list(range(0, 24)) hour_str = [] for x in hour: hour_str.append(str(x) + ":00") avg_type = ['Overall', 'Selection'] day = mapping_day(days_options.active) overall = average_checkins(day) selection = selection_avg_checkins(day, df['flag_5']) hour_str.reverse() overall.reverse() selection.reverse() data = {'hour': hour_str, 'Overall': overall, 'Selection': selection} source = ColumnDataSource(data=data) b = figure(y_range=hour_str, x_range=(0, 62), title="Checkin Counts Comparison", y_axis_label='Hour of Day', x_axis_label="Average Checkins", toolbar_location=None, tools="", plot_width=290, plot_height=550) b.hbar(y=dodge('hour', -0.22, range=b.y_range), right='Overall', height=0.35, source=source, color=Color_Palette[4], legend=value("Overall")) b.hbar(y=dodge('hour', +0.22, range=b.y_range), right='Selection', height=0.35, source=source, color=Color_Palette[1], legend=value("Selection")) b.outline_line_alpha = 0 b.legend.location = "center_right" b.legend.orientation = "vertical" b.yaxis.axis_line_color = None b.yaxis.major_tick_line_color = None b.yaxis.major_tick_out = 0 b.ygrid.grid_line_color = None b.xaxis.axis_line_color = None b.xaxis.minor_tick_line_color = None b.xaxis.major_tick_line_color = "#a7a7a7" return b
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 plt_bar2(hist_tabel, used, ylabel, xlabel, filename, wigth, xl, yl): w = 0.2 output_file(filename) gold = hist_tabel['gold'] pre = hist_tabel['pre'] up = [u.replace('http://dbpedia.org/ontology/', '') for u in used] goldl = [ gold['http://dbpedia.org/ontology/' + l] if 'http://dbpedia.org/ontology/' + l in gold.keys() else 0 for l in up ] prel = [ pre['http://dbpedia.org/ontology/' + l] if 'http://dbpedia.org/ontology/' + l in pre.keys() else 0 for l in up ] data = {'up': up, 'Gold': goldl, 'Preprocessing': prel} source = ColumnDataSource(data=data) p = figure(x_range=up, plot_height=800, plot_width=wigth, toolbar_location=None, tools="", x_axis_label=xl, y_axis_label=yl) p.vbar(x=dodge('up', -0.25, range=p.x_range), top='Gold', width=0.2, source=data, color="#c9d9d3", legend=value("Gold")) p.vbar(x=dodge('up', 0.0, range=p.x_range), top='Preprocessing', width=0.2, source=data, color="#718dbf", legend=value("Preprocessing")) p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.xaxis.major_label_orientation = 1 p.legend.orientation = "horizontal" p.legend.location = "top_left" save(p)
def _create_plot() -> (Figure, ColumnDataSource): """Utility function for creating and styling the bar plot.""" global source, aspects, stats pos_counts, neg_counts = \ ([stats.loc[(asp, pol, False), 'Quantity'] for asp in aspects] for pol in POLARITIES) np.seterr(divide='ignore') source = ColumnDataSource( data={ 'aspects': aspects, 'POS': pos_counts, 'NEG': neg_counts, 'log-POS': np.log2(pos_counts), 'log-NEG': np.log2(neg_counts) }) np.seterr(divide='warn') p = figure(plot_height=145, sizing_mode="scale_width", x_range=aspects, toolbar_location='right', tools='save, tap') rs = [ p.vbar(x=dodge('aspects', -0.207, range=p.x_range), top='log-POS', width=0.4, source=source, color="limegreen", legend=value('POS'), name='POS'), p.vbar(x=dodge('aspects', 0.207, range=p.x_range), top='log-NEG', width=0.4, source=source, color="orangered", legend=value('NEG'), name='NEG') ] for r in rs: p.add_tools( HoverTool(tooltips=[('Aspect', '@aspects'), (r.name, '@' + r.name)], renderers=[r])) p.add_layout( Title(text=' ' * 7 + 'Sentiment Count (log scale)', align='left', text_font_size='23px'), 'left') p.yaxis.ticker = [] p.y_range.start = 0 p.xgrid.grid_line_color = None p.xaxis.major_label_text_font_size = "20pt" p.legend.label_text_font_size = '20pt' return p, source
def test_basic(self): t = bt.dodge("foo", 0.5) assert isinstance(t, dict) assert set(t) == {"field", "transform"} assert t['field'] == "foo" assert isinstance(t['transform'], Dodge) assert t['transform'].value == 0.5 assert t['transform'].range is None
def test_with_range(self): r = FactorRange("a") t = bt.dodge("foo", 0.5, range=r) assert isinstance(t, dict) assert set(t) == {"field", "transform"} assert t['field'] == "foo" assert isinstance(t['transform'], Dodge) assert t['transform'].value == 0.5 assert t['transform'].range is r assert t['transform'].range.factors == ["a"]
output_file("bar_dodged.html") fruits = ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'] years = ['2015', '2016', '2017'] data = {'fruits' : fruits, '2015' : [2, 1, 4, 3, 2, 4], '2016' : [5, 3, 3, 2, 4, 6], '2017' : [3, 2, 4, 4, 5, 3]} source = ColumnDataSource(data=data) p = figure(x_range=fruits, y_range=(0, 10), plot_height=350, title="Fruit Counts by Year", toolbar_location=None, tools="") p.vbar(x=dodge('fruits', -0.25, range=p.x_range), top='2015', width=0.2, source=source, color="#c9d9d3", legend=value("2015")) p.vbar(x=dodge('fruits', 0.0, range=p.x_range), top='2016', width=0.2, source=source, color="#718dbf", legend=value("2016")) p.vbar(x=dodge('fruits', 0.25, range=p.x_range), top='2017', width=0.2, source=source, color="#e84d60", legend=value("2017")) p.x_range.range_padding = 0.1 p.xgrid.grid_line_color = None p.legend.location = "top_left" p.legend.orientation = "horizontal" show(p)
"noble gas" : "#eaeaea", "nonmetal" : "#f1d4Af", "transition metal" : "#599d7A", } source = ColumnDataSource(df) p = figure(plot_width=900, plot_height=500, title="Periodic Table (omitting LA and AC Series)", x_range=groups, y_range=list(reversed(periods)), toolbar_location=None, tools="hover") p.rect("group", "period", 0.95, 0.95, source=source, fill_alpha=0.6, legend="metal", color=factor_cmap('metal', palette=list(cmap.values()), factors=list(cmap.keys()))) text_props = {"source": source, "text_align": "left", "text_baseline": "middle"} x = dodge("group", -0.4, range=p.x_range) r = p.text(x=x, y="period", text="symbol", **text_props) r.glyph.text_font_style="bold" r = p.text(x=x, y=dodge("period", 0.3, range=p.y_range), text="atomic number", **text_props) r.glyph.text_font_size="8pt" r = p.text(x=x, y=dodge("period", -0.35, range=p.y_range), text="name", **text_props) r.glyph.text_font_size="5pt" r = p.text(x=x, y=dodge("period", -0.2, range=p.y_range), text="atomic mass", **text_props) r.glyph.text_font_size="5pt" p.text(x=["3", "3"], y=["VI", "VII"], text=["LA", "AC"], text_align="center", text_baseline="middle")