def visualization_actors_popularity(popularity_per_year, name): """ Function Description ------------- Uses the Bokeh library to plot the popularity of each movie in the actor's career over time. Input ------------------ popularity_per_year : A dataframe with each movie's metadata enacted by that actor. """ # output to static HTML file output_file("actor_popularity.html") # create a new plot with a title and axis labels p = figure(title=name + " Popularity over Time", x_axis_label='Date', y_axis_label='Revenue($)', y_range=(-(1e8), 5e8)) # add a line renderer with legend and line thickness p.line(popularity_per_year['Year'], popularity_per_year['Profit'], line_width=2) # Defining X ticks p.xaxis.ticker = FixedTicker(ticks=np.arange(1985, 2020, 5)) p.xgrid.ticker = FixedTicker(ticks=np.arange(1985, 2020, 5)) # show the results show(p)
def make_plot(src): p1 = figure(title="Gasverbruik per uur", x_range=(-0.5,23.5), y_range=(-0.5,6.5), x_axis_location="above", plot_width=900, plot_height=400, tools=TOOLS, toolbar_location='below', tooltips=[('Verbruik', '@aantal'),('Dag', '@dayofweek'),('Uur','@hour')] ) p1.grid.grid_line_color = None p1.axis.axis_line_color = None p1.axis.major_tick_line_color = None p1.axis.major_label_text_font_size = "5pt" p1.axis.major_label_standoff = 0 p1.xaxis.major_label_orientation = pi / 3 p1.xaxis.ticker = FixedTicker(ticks=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]) p1.yaxis.ticker = FixedTicker(ticks=[0,1,2,3,4,5,6]) p1.yaxis.major_label_overrides = {0:'Maandag', 1:'Dinsdag', 2:'Woensdag', 3:'Donderdag', 4:'Vrijdag', 5:'Zaterdag', 6:'Zondag'} p1.rect(x="hour", y="dayofweek", width=1, height=1, source=src, fill_color={'field': 'aantal', 'transform': mapper1}, line_color=None) color_bar1 = ColorBar(color_mapper=mapper1, major_label_text_font_size="5pt", ticker=BasicTicker(desired_num_ticks=len(colors)), formatter=PrintfTickFormatter(format="%d"), label_standoff=6, border_line_color=None, location=(0, 0)) p1.add_layout(color_bar1, 'right') return p1
def fixed_ticks(fig, ticks, axis='x'): if axis == 'x': fig.xaxis.ticker = FixedTicker(ticks=ticks) elif axis == 'y': fig.yaxis.ticker = FixedTicker(ticks=ticks) elif axis == 'both': fig.xaxis.ticker = FixedTicker(ticks=ticks) fig.yaxis.ticker = FixedTicker(ticks=ticks)
def visualization_genre_by_season(dict_release_overview, year=2017): """ Function Description ------------- Uses the Bokeh library to plot the monthly distribution of films by genre Input ------------------ dict_release_overview : A dictionary of lists of dictionaries that has number of releases for each genre and month """ month_mapping = {k: v for k, v in enumerate(calendar.month_abbr)} month_mapping.pop(0) p = figure(title='Releases by Genre: {}'.format(year), x_axis_label='Months', y_axis_label='Releases') max_v, count = 0, 0 colors = ['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c', '#fb9a99'] for genre, list_releases in dict_release_overview.items(): x, y = [], [] # add month numbers in x and corresponding number of releases on y axis for the genre for dict_release in list_releases: x.append(dict_release['month_num']) y.append(dict_release['num_of_releases']) if dict_release['num_of_releases'] > max_v: max_v = dict_release['num_of_releases'] # add a line renderer with legend and line thickness p.line(x, y, legend=genre, line_width=2, color=colors[count]) p.xaxis.major_label_overrides = month_mapping # Defining X ticks p.xaxis.ticker = FixedTicker(ticks=list(month_mapping.keys())) p.xgrid.ticker = FixedTicker(ticks=list(month_mapping.keys())) # Defining y ticks p.yaxis.ticker = FixedTicker(ticks=np.arange(0, max_v + 50, 50)) p.ygrid.ticker = FixedTicker(ticks=np.arange(0, max_v + 50, 50)) p.y_range.end = max_v + 50 count = count + 1 # output to static HTML file output_file('genre_by_season.html') show(p)
def OpenMP(graph): curdoc().clear() OpenMP = pd.read_csv("OpenMP.csv") graph.xaxis.ticker = FixedTicker( ticks=[160, 320, 640, 960, 1280, 1600, 1920, 2240, 2560, 2880]) names = [OpenMP.columns[i] for i in range(1, 8)] for i in range(7): source = ColumnDataSource( data={ 'particles': OpenMP['particles'], 'time': OpenMP[names[i]], 'name': [names[i] for j in range(10)] }) graph.line('particles', 'time', source=source, legend=names[i], line_width=2, color=colors[i]) circle = graph.circle('particles', 'time', source=source, size=6, color=colors[i]) graph.xaxis.axis_label = "# Particles" graph.yaxis.axis_label = "time (ms)" graph.legend.location = "top_left" graph.title.text = "OpenMP Backend" curdoc().add_root(column(select, graph))
def δ_2d(model, t, fig=None, show=True, filename=None): X = range(model.N) # X = np.arange(0, model.T, model.T / model.N) if fig is None: fig = figure(x_range=(min(X), max(X)), y_range=[-0.05, 1.0], plot_width=400, plot_height=200, tools=()) fig.yaxis.ticker = FixedTicker(ticks=[1]) fig.yaxis.major_tick_out = 0 fig.outline_line_color = None fig.xaxis.major_tick_line_color = None fig.xaxis.major_label_text_color = None fig.xaxis.axis_line_color = None # fig.xaxis.ticker = FixedTicker(ticks=list(X)) # fig.xaxis.major_tick_out = 2 fig.line([min(X), max(X)], (0, 0), line_color='#888888', line_width=1) for tick in X: fig.line([tick, tick], (0, -0.01), line_color='#888888', line_width=1) fig.line(X, model.δ_history[t], line_color='black', line_width=5) if filename is not None: export_png(fig, filename='figures/{}.png'.format(filename)) if show: bkp.show(fig)
def initialize_sc_figure(league, curr_week): # todo docstring sc_hover = HoverTool(tooltips=[ ('Week', '@x'), ('Owner', '@owner'), ('Score', '@y{*00.00}'), ]) # try plotting just scores first plot = figure(plot_height=600, plot_width=1000, title='{} - {} Regular Season'.format( league.settings.name, year_input.value), x_axis_label='Week', y_axis_label='Scores', tools=[ sc_hover, ResetTool(), BoxZoomTool(), WheelZoomTool(), SaveTool(), PanTool() ]) plot.xaxis.ticker = FixedTicker(ticks=[i for i in range(1, curr_week + 1)]) return plot
def _plot_parallel(ax, diverging_mask, _posterior, var_names, figsize, show): if ax is None: tools = rcParams["plot.bokeh.tools"] output_backend = rcParams["plot.bokeh.output_backend"] dpi = rcParams["plot.bokeh.figure.dpi"] ax = bkp.figure( width=int(figsize[0] * dpi), height=int(figsize[1] * dpi), output_backend=output_backend, tools=tools, ) non_div = list(_posterior[:, ~diverging_mask].T) x_non_div = [list(range(len(non_div[0]))) for _ in range(len(non_div))] ax.multi_line( x_non_div, non_div, line_color="black", line_alpha=0.05, ) if np.any(diverging_mask): div = list(_posterior[:, diverging_mask].T) x_non_div = [list(range(len(div[0]))) for _ in range(len(div))] ax.multi_line(x_non_div, div, color="lime", line_width=1, line_alpha=0.5) ax.xaxis.ticker = FixedTicker(ticks=list(range(len(var_names)))) ax.xaxis.major_label_overrides = dict(zip(map(str, range(len(var_names))), map(str, var_names))) ax.xaxis.major_label_orientation = np.pi / 2 if show: bkp.show(ax) return ax
def apply(self, func, **kwargs): # create a figure with specified layout d = [[] for _ in range(len(self.layout))] for i, row in enumerate(self.layout): is_bottom = ((i + 1) == len(self.layout)) for j, seqid in enumerate(row): is_left = (j == 0) if seqid is not None: contig_size = len(self.genome[seqid]) px = int(contig_size * 1e-6 * self.plot_width_per_mb) px += self.min_border_left px += self.min_border_right try: yrange = s1.y_range except NameError: yrange = None s1 = figure(width=px, plot_height=self.figheight, min_border_left=self.min_border_left, min_border_right=self.min_border_right, tools=self.tools, title=self.chrom_label_func(seqid), y_range=yrange, x_range=(1, contig_size)) s1.xaxis.ticker = FixedTicker( ticks=np.arange(0, contig_size, self.major_tick_dist)) s1.xaxis[0].formatter = NumeralTickFormatter(format="0a.0") # handle general plot things specific to genome not data if self.pfunc is not None: self.pfunc(seqid, s1) # function lives here func(self.genome[seqid], s1, is_left=is_left, is_bottom=is_bottom, **kwargs) d[i].append(s1) else: d[i].append(None) # put the subplots in a grid plot p = gridplot(d, toolbar_location="left", sizing_mode='fixed', plot_width=None) show(p)
def make_color_array(self): dc = self.data[self.colorcol] colmax = np.amax(dc) colmin = np.amin(dc) delt = 1. * (colmax - colmin) / (len(self.colortable) - 1) bins = (dc - colmin) // delt bins = bins.astype(np.int8) self.binedges = np.arange(colmin, colmax + delt, (colmax - colmin) / 8) colors = self.colortable[bins] self.color_array = colors self.data['colors'] = colors self.ticker = FixedTicker(ticks=self.binedges) self.mapper = LinearColorMapper(palette=self.colortable) if self.color_bar is not None: self.color_bar.ticker = self.ticker self.color_bar.color_mapper = self.mapper #self.formatter = NumeralTickFormatter(format="%5.2e") self.mapper.low = colmin self.mapper.high = colmax print("Done with color array")
def plot_ulid(ulid): from .models import Entry from bokeh.plotting import figure from bokeh.models.tickers import FixedTicker qs = Entry.objects.filter(ulid=ulid, item='OpticalPower') vl = qs.values_list('value', flat=True) power = np.array(list(vl)) qs = Entry.objects.filter(ulid=ulid, item='Pre-FEC_ber') vl = qs.values_list('value', flat=True) prefecber = np.array(list(vl)) qs = Entry.objects.filter(ulid=ulid, item='Post-FEC_ber') vl = qs.values_list('value', flat=True) postfecber = np.array(list(vl)) plot = figure(title= 'BER plot', x_axis_label= 'Pin', y_axis_label= 'BER', plot_width =400, plot_height =400) plot.scatter(power, -np.log10(-np.log10(prefecber)), legend= 'Pre-FEC', line_width = 2, color='red') plot.scatter(power, -np.log10(-np.log10(postfecber)), legend= 'Post-FEC', line_width = 2, color='blue') plot.yaxis.ticker = -np.log10(-np.log10(10 ** np.arange(-13, -3, 1.0))) plot.ygrid.ticker = FixedTicker(ticks=-np.log10(-np.log10(10 ** np.arange(-13, -3, 1.0)))) return plot
def initialize_ew_figure(league, curr_week): # todo docstring ew_hover = HoverTool(tooltips=[ ('Week', '@x'), ('Owner', '@owner'), ('Expected Wins', '@y{*0.000}'), ]) # plotting wins and expected wins in the second tab plot = figure(plot_height=600, plot_width=1000, title='{} - {} Regular Season'.format( league.settings.name, year_input.value), x_axis_label='Week', y_axis_label='Expected Wins', tools=[ ew_hover, ResetTool(), BoxZoomTool(), WheelZoomTool(), SaveTool(), PanTool() ]) plot.xaxis.ticker = FixedTicker(ticks=[i for i in range(1, curr_week + 1)]) return plot
def _axis_properties(self, axis, key, plot, element): """ Returns a dictionary of axis properties depending on the specified axis. """ axis_props = {} if ((axis == 'x' and self.xaxis in ['bottom-bare', 'top-bare']) or (axis == 'y' and self.yaxis in ['left-bare', 'right-bare'])): axis_props['axis_label'] = '' axis_props['major_label_text_font_size'] = '0pt' axis_props['major_tick_line_color'] = None axis_props['minor_tick_line_color'] = None else: rotation = self.xrotation if axis == 'x' else self.yrotation if rotation: axis_props['major_label_orientation'] = np.radians(rotation) ticker = self.xticks if axis == 'x' else self.yticks if isinstance(ticker, Ticker): axis_props['ticker'] = ticker elif isinstance(ticker, int): axis_props['ticker'] = BasicTicker(desired_num_ticks=ticker) elif isinstance(ticker, list): if all(isinstance(t, tuple) for t in ticker): pass else: axis_props['ticker'] = FixedTicker(ticks=ticker) return axis_props
def plot_parallel(ax, diverging_mask, _posterior, var_names, figsize, backend_config, backend_kwargs, show): """Bokeh parallel plot.""" if backend_config is None: backend_config = {} backend_config = { **backend_kwarg_defaults( ("bounds_x_range", "plot.bokeh.bounds_x_range"), ("bounds_y_range", "plot.bokeh.bounds_y_range"), ), **backend_config, } if backend_kwargs is None: backend_kwargs = {} backend_kwargs = { **backend_kwarg_defaults(("dpi", "plot.bokeh.figure.dpi"), ), **backend_kwargs, } dpi = backend_kwargs.pop("dpi") if ax is None: backend_kwargs.setdefault("width", int(figsize[0] * dpi)) backend_kwargs.setdefault("height", int(figsize[1] * dpi)) ax = bkp.figure(**backend_kwargs) non_div = list(_posterior[:, ~diverging_mask].T) x_non_div = [list(range(len(non_div[0]))) for _ in range(len(non_div))] ax.multi_line( x_non_div, non_div, line_color="black", line_alpha=0.05, ) if np.any(diverging_mask): div = list(_posterior[:, diverging_mask].T) x_non_div = [list(range(len(div[0]))) for _ in range(len(div))] ax.multi_line(x_non_div, div, color="lime", line_width=1, line_alpha=0.5) ax.xaxis.ticker = FixedTicker(ticks=list(range(len(var_names)))) ax.xaxis.major_label_overrides = dict( zip(map(str, range(len(var_names))), map(str, var_names))) ax.xaxis.major_label_orientation = np.pi / 2 ax.x_range = DataRange1d(bounds=backend_config["bounds_x_range"], min_interval=2) ax.y_range = DataRange1d(bounds=backend_config["bounds_y_range"], min_interval=5) show_layout(ax, show) return ax
def ridgeplot(courses_obj): # first format 'courses_obj' into 'probly' DataFrame format # courses_obj: [{'course_name': 'Calculus...', ...}, ...] grades = [[100*y[2]/y[3] for y in x['assignments']] for x in courses_obj] # turn this list of lists into a complete NumPy array length = len(sorted(grades, key=len, reverse=True)[0]) grades = np.array([xi+[None]*(length-len(xi)) for xi in grades], dtype='float') columns = [x['course_name'] for x in courses_obj] grades = grades.transpose() probly = pd.DataFrame(grades, columns=columns) cats = list(reversed(probly.keys())) palette = [cc.rainbow[i*15] for i in range(17)] x = np.linspace(-20,110, 500) source = ColumnDataSource(data=dict(x=x)) p = figure(y_range=cats, plot_width=900, plot_height = 300, x_range=(-5, 120))#, toolbar_location=None) for i, cat in enumerate(reversed(cats)): adjusted = probly[cat].replace([np.inf, -np.inf], np.nan).dropna(how="all") if adjusted.size == 1 or pd.unique(adjusted).size == 1: # this means we can't compute continue pdf = gaussian_kde(adjusted) #p = figure(plot_width=400, plot_height=400) #p.line(x, pdf(x)) y = ridge(cat, pdf(x), scale=2) #p.line(x, y, color='black') #show(p) source.add(y, cat) p.patch('x', cat, color=palette[i], alpha=0.6, line_color="black", source=source) p.outline_line_color = None p.background_fill_color = "#efefef" p.tools = [PanTool(), CrosshairTool(), HoverTool(), SaveTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()] ticks = list(np.array([np.array([0,3,7])+i*10 for i in range(10)]).flatten()) + [100] p.xaxis.ticker = FixedTicker(ticks=ticks) p.xaxis.formatter = PrintfTickFormatter(format="%d") p.xaxis.axis_label = "Your Grade Distribution" p.yaxis.axis_label = "Your Courses" p.ygrid.grid_line_color = None p.xgrid.grid_line_color = "Grey" p.xgrid.ticker = p.xaxis[0].ticker p.axis.minor_tick_line_color = None p.axis.major_tick_line_color = None p.axis.axis_line_color = None p.y_range.range_padding = 0.12 return p
def _set_initial_figure(self): boxzoom = BoxZoomTool() pan = PanTool(dimensions='width') wheelzoom = WheelZoomTool(dimensions='width') reset = ResetTool() undo = UndoTool() tools = [pan, boxzoom, wheelzoom, reset, undo] p = figure(plot_width=1000, plot_height=300, tools=tools) p.toolbar.active_drag = pan p.toolbar.active_scroll = wheelzoom p.toolbar.active_tap = None p.toolbar.logo = None x_range_obj = Range1d(start=0, end=25) p.x_range = x_range_obj p.y_range = Range1d(start=-0.1, end=1.1) initial_ticks = list(range(30)) x_ticker = FixedTicker(ticks=initial_ticks) p.xaxis.ticker = x_ticker p.xgrid.ticker = x_ticker initial_ticks = list([i / 10 for i in range(11)]) y_ticker = FixedTicker(ticks=initial_ticks) p.yaxis.ticker = y_ticker p.ygrid.ticker = y_ticker p.title.text = 'Segment Matching Of Structures' p.title.align = 'center' p.yaxis.axis_label = 'Score' p.x("xs", 'ys', source=self.CDS, line_color='color', line_dash='solid', line_width=2) p.multi_line(xs="xs_line", ys='ys_line', color='color_line', source=self.line_CDS, line_width=2) return p, x_range_obj, x_ticker
def karyotype( x_datas, y_datas, names=None, colors=None, alpha=0.2, chrom_data=_chrom_data_, **kwargs): """Create a heatmap from three columns. :param x: x-axis coordinates (chromosome position) :param y: y-axis coordinates (chromosome) :param name: title for z-axis. :param colors: colours to plot tics for each data series. :param alpha: alpha level (transparency) with which to plot tics. :params chrom_data: a dataframe (or ndarray) with fields `chrom`, and `length` used to plot chromosome outline rectangles. Chromosomes will be plotted vertically (top to bottom) in the order given by this input. :param kwargs: kwargs for bokeh figure. :returns: a bokeh plot. """ if names is None: names = [None] * len(x_datas) if colors is None: colors = [None] * len(x_datas) defaults = { "output_backend": "webgl", "height": 300, "width": 600} defaults.update(kwargs) p = figure(**defaults) width = 0.8 chrom_order = pd.Series(range(1, len(chrom_data) + 1)) p.rect( chrom_data["length"] // 2, chrom_order, chrom_data["length"], width, fill_color='white', line_color='black') plot_order = dict(zip(chrom_data['chrom'], chrom_order)) for x, y, name, color in zip(x_datas, y_datas, names, colors): y = np.array([plot_order[i] for i in y]) kw = {'alpha': alpha} if name is not None: kw['legend_label'] = name if color is not None: kw['color'] = color p.segment( x, y - width / 2, x, y + width / 2, **kw) # set up the axes p.xaxis.formatter.use_scientific = False p.yaxis.ticker = FixedTicker() p.yaxis.ticker.ticks = chrom_order p.yaxis.major_label_overrides = {v: k for k, v in plot_order.items()} p.x_range = Range1d( start=0, end=max(chrom_data['length']), bounds=(0, max(chrom_data['length']))) miny, maxy = 0, len(chrom_data) + 1 p.y_range = Range1d( start=miny, end=maxy, bounds=(miny, maxy)) return p
def update_plot_after_montage_change(self): self.fig.title.text = self.title goto_sample = int(self.fs * self.loc_sec) page_width_samples = int(self.page_width_secs * self.fs) hw = half_width_epoch_sample = int(page_width_samples / 2) s0 = limit_sample_check(goto_sample - hw, self.signals) s1 = limit_sample_check(goto_sample + hw, self.signals) window_samples = s1 - s0 signal_view = self.signals[:, s0:s1] inmontage_view = np.dot(self.current_montage_instance.V.data, signal_view) self.ch_start = 0 self.ch_stop = inmontage_view.shape[0] numRows = inmontage_view.shape[0] # ??? # print('numRows: ', numRows) data = inmontage_view[self.ch_start:self.ch_stop, :] # note transposed # really just need to reset the labels ticklocs = [] ## xlim(*xlm) # xticks(np.linspace(xlm, 10)) dmin = data.min() dmax = data.max() dr = (dmax - dmin) * 0.7 # Crowd them a bit. y0 = dmin y1 = (numRows - 1) * dr + dmax ## ylim(y0, y1) ticklocs = [ii * dr for ii in range(numRows)] ticklocs.reverse() # inplace bottom = -dr / 0.7 top = (numRows - 1) * dr + dr / 0.7 self.y_range.start = bottom self.y_range.end = top # self.fig.y_range = Range1d(bottom, top) # print("ticklocs:", ticklocs) offsets = np.zeros((numRows, 2), dtype=float) offsets[:, 1] = ticklocs self.ticklocs = ticklocs # self.time = t ylabels = self.current_montage_instance.montage_labels ylabel_dict = dict(zip(ticklocs, ylabels)) # print('ylabel_dict:', ylabel_dict) self.fig.yaxis.ticker = FixedTicker( ticks=ticklocs) # can also short cut to give list directly self.fig.yaxis.formatter = FuncTickFormatter(code=""" var labels = %s; return labels[tick]; """ % ylabel_dict)
def _axis_properties(self, axis, key, plot, dimension, ax_mapping={ 'x': 0, 'y': 1 }): """ Returns a dictionary of axis properties depending on the specified axis. """ axis_props = {} if ((axis == 'x' and self.xaxis in ['bottom-bare', 'top-bare']) or (axis == 'y' and self.yaxis in ['left-bare', 'right-bare'])): axis_props['axis_label'] = '' axis_props['major_label_text_font_size'] = '0pt' axis_props['major_tick_line_color'] = None axis_props['minor_tick_line_color'] = None else: rotation = self.xrotation if axis == 'x' else self.yrotation if rotation: axis_props['major_label_orientation'] = np.radians(rotation) ticker = self.xticks if axis == 'x' else self.yticks if isinstance(ticker, Ticker): axis_props['ticker'] = ticker elif isinstance(ticker, int): axis_props['ticker'] = BasicTicker(desired_num_ticks=ticker) elif isinstance(ticker, (tuple, list)): if all(isinstance(t, tuple) for t in ticker): pass else: axis_props['ticker'] = FixedTicker(ticks=ticker) if FuncTickFormatter is not None and ax_mapping and dimension: formatter = None if dimension.value_format: formatter = dimension.value_format elif dimension.type in dimension.type_formatters: formatter = dimension.type_formatters[dimension.type] if formatter: msg = ('%s dimension formatter could not be ' 'converted to tick formatter. ' % dimension.name) try: formatter = FuncTickFormatter.from_py_func(formatter) except RuntimeError: self.warning(msg + 'Ensure Flexx is installed ' '("conda install -c bokeh flexx" or ' '"pip install flexx")') except Exception as e: error = 'Pyscript raised an error: {0}'.format(e) error = error.replace('%', '%%') self.warning(msg + error) else: axis_props['formatter'] = formatter return axis_props
def set_yaxis_tick_values(self, values): """Set y-axis tick values. Args: values (list): Values for the axis ticks. Returns: Current chart object """ self._chart.figure.yaxis.ticker = FixedTicker(ticks=values) return self._chart
def plotarray(xvar,yvar,titlelab,xlab,ylab): p = [0] * len(yvar) for i in (range(len(p))): p[i] = figure(title = titlelab, x_axis_label = xlab, y_axis_label =ylab, plot_width=250, plot_height=250) p[i].line(xvar[i], yvar[i], line_width=1, color="navy") p[i].title.align = 'center' p[i].xaxis.ticker = FixedTicker(ticks=[round(min(xvar[-1]),3), round((max(xvar[-1]))/2,3), round(max(xvar[-1]),3)]) return p
def set_xaxis_tick_values(self, values): """Set x-axis tick values. Args: values (list or DatetimeIndex): Values for the axis ticks. Returns: Current chart object """ self._chart.figure.xaxis.ticker = FixedTicker(ticks=values) return self._chart
def display_confusion_bokeh(ref_intervals, sys_intervals, global_range, confusion_data=None, colors=[["#9933FF"], ["#FF00FF"]], plot_size=[900, 250]): from bokeh.io import output_notebook from bokeh.plotting import figure, show, output_file, ColumnDataSource from bokeh.models import Range1d, HoverTool, Legend from bokeh.models.tickers import FixedTicker output_notebook() y_positions = np.array([2, 1]) intervals_list = [ref_intervals, sys_intervals] interval_range = global_range[1] - global_range[0] x_range = Range1d(-(interval_range * 0.05), interval_range * 1.05) if confusion_data is not None: y_range = Range1d(0, 4) con_intervals, confusion_vector, confusion_mapping = confusion_data colors.append([confusion_mapping[x][1] for x in confusion_vector]) intervals_list.append(con_intervals) y_positions = np.append(y_positions + 1, 1) else: y_range = Range1d(0, 3) height = 0.6 default_options = {"line_color": "black", "line_width": 1} p = figure(x_range=x_range, y_range=y_range, plot_width=plot_size[0], plot_height=plot_size[1], title="Confusion Visualisation", title_location='above') for interval, y_pos, col in zip(intervals_list, y_positions, colors): IntervalCompute.broken_barh(interval, y_pos, height, fig=p, color=col, options=default_options) labels = ["Reference", "System_Output", "Confusion"] p.xgrid.grid_line_color = None p.xaxis.axis_label = "Frames" p.yaxis.ticker = FixedTicker(ticks=y_positions[::-1]) p.yaxis.major_label_overrides = { str(i): label for i, label in zip(y_positions, labels) } p.background_fill_color = (234, 234, 234) p.border_fill_color = (255, 255, 255) show(p)
def setup_timeline_axis(plot: figure) -> None: """ :param plot: :return: """ start_date, end_date = plot.x_range.start, plot.x_range.end # 主目盛り幅の作成 dt_dick = list(pd.date_range(start=start_date, end=end_date, freq='6M')) dt_dick_values = pd.to_datetime(dt_dick).astype(int) dt_dick_values = list(dt_dick_values / 10**6) # 補助目盛り幅の作成 minor_dt_dick = list( pd.date_range(start=start_date, end=end_date, freq='6M')) minor_dt_dick_values = pd.to_datetime(minor_dt_dick).astype(int) minor_dt_dick_values = list(minor_dt_dick_values / 10**6) # 軸の設定 plot.xaxis.axis_label = "Creation date of the PEPs " \ + "(Some PEPs don't have 'Created' field)" plot.xaxis.ticker = FixedTicker(ticks=dt_dick_values) plot.yaxis.visible = False # 目盛線の設定 plot.xgrid.ticker = FixedTicker(ticks=minor_dt_dick_values, num_minor_ticks=1) format_datetime_code = """ var date = new Date(tick) var month = date.getUTCMonth(date) if ( month == 0) { // January return date.getUTCFullYear(date) } else { return "" } """ plot.xaxis.formatter = FuncTickFormatter(code=format_datetime_code)
def δ_2d_dashed(model, t, dashed_t=None, fig=None, show=True, legend=None, dashed_legend=None, filename=None): X = range(model.N) # X = np.arange(0, model.T, model.T / model.N) if fig is None: fig = figure(x_axis_label="Time-step", x_range=(min(X), max(X)), y_axis_label="Prediction error", y_range=[-0.1, 1.0], plot_width=400, plot_height=300, tools=()) fig.yaxis.ticker = FixedTicker(ticks=[0, 1]) fig.yaxis.major_tick_out = 2 fig.xaxis.major_tick_line_color = None fig.xaxis.major_label_text_color = None fig.xaxis.axis_line_color = None fig.outline_line_color = None fig.line([min(X), max(X)], (0, 0), line_color='#888888', line_width=1) for tick in X: fig.line([tick, tick], (0, -0.01), line_color='#888888', line_width=1) fig.line(X, model.δ_history[t - 1], legend=legend, line_color='black', line_width=1) if dashed_t is not None: fig.line(X, model.δ_history[dashed_t - 1], legend=dashed_legend, line_color='black', line_dash='dotted', line_width=1) fig.legend.border_line_color = None fig.legend.location = 'top_left' if filename is not None: export_png(fig, filename='figures/{}.png'.format(filename)) if show: bkp.show(fig)
def make_plot(src): tooltips = [ ("index", "$index"), ("Business", "@Business_Name"), ("R2B: Email sponsorship/promotion", "@R2B_email_sponsorship_promotion"), ("R2B: Provide Resources", "@R2B_provide_resources"), ("R2B: Liason", "@R2B_liason"), ("B2R: Event participation", "@B2R_event_participation"), ("B2R: Sponsorship/donation", "@B2R_sponsorship_donation"), ("B2R: Share info", "@B2R_share_business_information"), ("B2R: Volunteer", "@B2R_volunteer"), ("Use RVMS resources", "@B2R_use_RVMS_resources"), ("Industry", "@2017_NAICS_US_Title"), ("NAICS Code", "@NAICS_Code"), ] p = figure(title="Business Engagement Matrix", x_axis_label='Business to RVMS', y_axis_label='RVMS to Business', x_range=(0, 6), y_range=(0, 4), tooltips=tooltips) # Ticks p.xaxis.ticker = FixedTicker(ticks=[1, 2, 3, 4, 5]) p.yaxis.ticker = FixedTicker(ticks=[1, 2, 3, 4]) # Grid lines p.xgrid.ticker = FixedTicker(ticks=[1, 2, 3, 4, 5]) p.ygrid.ticker = FixedTicker(ticks=[1, 2, 3, 4]) p.scatter(x='B2R_score_noise', y='R2B_score_noise', fill_color='color', radius='radius', source=src) return p
def make_plot_horizontaal(src): p = figure(tools=TOOLS, background_fill_color="#ffffff", plot_width=846, plot_height=400, x_range=(-0.5,23.5), tooltips=[('Verbruik', '@difference'),('Uur','@hour')]) p.vbar(x='hour', bottom=0, top='difference', source=src, width=0.96, color={'field': 'difference', 'transform': mapper2},) p.y_range.start = 0 p.xaxis.axis_label = 'Uur van de dag' p.yaxis.axis_label = 'Verbruik' p.grid.grid_line_color="#ffffff" p.xaxis.ticker = FixedTicker(ticks=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]) return p
def _axis_properties(self, axis, key, plot, dimension=None, ax_mapping={'x': 0, 'y': 1}): """ Returns a dictionary of axis properties depending on the specified axis. """ axis_props = {} if ((axis == 'x' and self.xaxis in ['bottom-bare', 'top-bare']) or (axis == 'y' and self.yaxis in ['left-bare', 'right-bare'])): axis_props['axis_label'] = '' axis_props['major_label_text_font_size'] = value('0pt') axis_props['major_tick_line_color'] = None axis_props['minor_tick_line_color'] = None else: labelsize = self._fontsize('%slabel' % axis).get('fontsize') if labelsize: axis_props['axis_label_text_font_size'] = labelsize ticksize = self._fontsize('%sticks' % axis, common=False).get('fontsize') if ticksize: axis_props['major_label_text_font_size'] = value(ticksize) rotation = self.xrotation if axis == 'x' else self.yrotation if rotation: axis_props['major_label_orientation'] = np.radians(rotation) ticker = self.xticks if axis == 'x' else self.yticks if isinstance(ticker, Ticker): axis_props['ticker'] = ticker elif isinstance(ticker, int): axis_props['ticker'] = BasicTicker(desired_num_ticks=ticker) elif isinstance(ticker, (tuple, list)): if all(isinstance(t, tuple) for t in ticker): pass else: axis_props['ticker'] = FixedTicker(ticks=ticker) if FuncTickFormatter is not None and ax_mapping and dimension: formatter = None if dimension.value_format: formatter = dimension.value_format elif dimension.type in dimension.type_formatters: formatter = dimension.type_formatters[dimension.type] if formatter: msg = ('%s dimension formatter could not be ' 'converted to tick formatter. ' % dimension.name) jsfunc = py2js_tickformatter(formatter, msg) if jsfunc: formatter = FuncTickFormatter(code=jsfunc) axis_props['formatter'] = formatter return axis_props
def _plot_parallel(ax, diverging_mask, _posterior, var_names, figsize, show): if ax is None: tools = ",".join([ "pan", "wheel_zoom", "box_zoom", "lasso_select", "poly_select", "undo", "redo", "reset", "save,hover", ]) ax = bkp.figure( width=int(figsize[0] * 90), height=int(figsize[1] * 90), output_backend="webgl", tools=tools, ) non_div = list(_posterior[:, ~diverging_mask].T) x_non_div = [list(range(len(non_div[0]))) for _ in range(len(non_div))] ax.multi_line( x_non_div, non_div, line_color="black", line_alpha=0.05, ) if np.any(diverging_mask): div = list(_posterior[:, diverging_mask].T) x_non_div = [list(range(len(div[0]))) for _ in range(len(div))] ax.multi_line(x_non_div, div, color="lime", line_width=1, line_alpha=0.5) ax.xaxis.ticker = FixedTicker(ticks=list(range(len(var_names)))) ax.xaxis.major_label_overrides = dict( zip(map(str, range(len(var_names))), map(str, var_names))) ax.xaxis.major_label_orientation = np.pi / 2 if show: bkp.show(ax) return ax
def plot_parallel(ax, diverging_mask, _posterior, var_names, figsize, backend_kwargs, show): """Bokeh parallel plot.""" if backend_kwargs is None: backend_kwargs = {} backend_kwargs = { **backend_kwarg_defaults( ("tools", "plot.bokeh.tools"), ("output_backend", "plot.bokeh.output_backend"), ("dpi", "plot.bokeh.figure.dpi"), ), **backend_kwargs, } dpi = backend_kwargs.pop("dpi") if ax is None: ax = bkp.figure(width=int(figsize[0] * dpi), height=int(figsize[1] * dpi), **backend_kwargs) non_div = list(_posterior[:, ~diverging_mask].T) x_non_div = [list(range(len(non_div[0]))) for _ in range(len(non_div))] ax.multi_line( x_non_div, non_div, line_color="black", line_alpha=0.05, ) if np.any(diverging_mask): div = list(_posterior[:, diverging_mask].T) x_non_div = [list(range(len(div[0]))) for _ in range(len(div))] ax.multi_line(x_non_div, div, color="lime", line_width=1, line_alpha=0.5) ax.xaxis.ticker = FixedTicker(ticks=list(range(len(var_names)))) ax.xaxis.major_label_overrides = dict( zip(map(str, range(len(var_names))), map(str, var_names))) ax.xaxis.major_label_orientation = np.pi / 2 if backend_show(show): bkp.show(ax) return ax