def get_figure(self): if not hasattr(self, "graph"): self.get_optimal_bifurcation_point() self.make_line_data() self.make_point_data() fig = figure(match_aspect=True) try: fig.circle(x='x_values', y='y_values', color='colors', size=15, alpha=0.8, legend_group='legend', source=self.point_source) except: fig.circle(x='x_values', y='y_values', color='colors', size=15, alpha=0.8, source=self.point_source) fig.segment(x0="x0", y0="y0", x1="x1", y1="y1", color="navy", line_width=3, source=self.segment_source) fig.xaxis.ticker = SingleIntervalTicker(interval=1) fig.yaxis.ticker = SingleIntervalTicker(interval=1) delattr(self, "graph") return fig
def add_axes(self, plot): """ Adds axis to Bokeh plot Obj :param plot: Bokeh plot obj. from get_plot method :return: Bokeh plot obj """ min_x_range, max_x_range = self.get_x_ranges() min_y_range, max_y_range = self.get_y_ranges(self.plot_data1) min_y2_range, max_y2_range = self.get_y_ranges(self.plot_data2) x_interval = roundup(max_x_range) y_interval = roundup(max_y_range) y2_interval = roundup(max_y2_range) xaxis = LinearAxis(SingleIntervalTicker(interval=x_interval), axis_label=self.xlabel, **AXIS_FORMATS) yaxis = LinearAxis(SingleIntervalTicker(interval=y_interval), axis_label=self.ylabel, **AXIS_FORMATS) yaxis2 = LinearAxis(SingleIntervalTicker(interval=y2_interval), y_range_name="y_range2", axis_label=self.ylabel2, **AXIS_FORMATS) plot.add_layout(xaxis, 'below') plot.add_layout(yaxis, 'left') plot.add_layout(yaxis2, 'right') return plot
def create_linegraph(src): p2 = figure(x_range=(2012, 2020), y_range=(0, 100000), plot_height=600, plot_width=800, tools='pan,box_zoom,reset,save', title='Average Price by Year', title_location='above') x_title = 'Year' y_title = 'Avg_Price (dollars)' p2.title.text_font_size = '25px' p2.title.text_color = 'black' p2.xaxis.axis_label = x_title p2.yaxis.axis_label = y_title p2.xaxis.formatter.use_scientific = False p2.yaxis.formatter.use_scientific = False p2.xaxis.formatter = NumeralTickFormatter(format=('0')) p2.yaxis.formatter = NumeralTickFormatter(format=('$0,0.00')) p2.background_fill_color = "black" p2.background_fill_alpha = 0.05 p2.xgrid.grid_line_color = None p2.ygrid.grid_line_color = None p2.outline_line_width = 2 p2.outline_line_alpha = 0.8 p2.outline_line_color = "red" p2.xaxis.ticker = SingleIntervalTicker(interval=1) p2.yaxis.ticker = SingleIntervalTicker(interval=10000) p2.line(x='year', y='avg_price', line_width=3, source=src) return p2
def create_figure(src): x_title = 'Mileage (miles)' y_title = 'Price (dollars)' p = figure(x_range=(0, 1100000), y_range=(0, 100000), plot_height=400, plot_width=800, tools='pan,box_zoom,reset,save') p.title.text_font_size = '25px' p.title.text_color = 'black' p.xaxis.axis_label = x_title p.yaxis.axis_label = y_title p.xaxis.formatter.use_scientific = False p.yaxis.formatter.use_scientific = False p.xaxis.formatter = NumeralTickFormatter(format=('0[.]0a')) p.yaxis.formatter = NumeralTickFormatter(format=('$0,0.00')) p.background_fill_color = "black" p.background_fill_alpha = 0.05 p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None p.outline_line_width = 2 p.outline_line_alpha = 0.8 p.outline_line_color = "red" p.xaxis.ticker = SingleIntervalTicker(interval=100000) p.yaxis.ticker = SingleIntervalTicker(interval=10000) p.circle(x='mileage', y='price', size=5, color="red", alpha=0.8, source=src) return p
def construct_line(source, value_string, line_color=BLUE): xdr = Range1d(1990, 2013) ydr = Range1d(0, 100) line_plot = Plot(x_range=xdr, y_range=ydr, title="", plot_width=250, plot_height=150, min_border_top=10, min_border_left=50, **PLOT_FORMATS) xaxis = LinearAxis(SingleIntervalTicker(interval=50), **AXIS_FORMATS) yaxis = LinearAxis(SingleIntervalTicker(interval=10), **AXIS_FORMATS) line_plot.add_layout(xaxis, 'left') line_plot.add_layout(yaxis, 'below') line = Line( x='year', y=value_string, line_width=5, line_cap="round", line_color=line_color, ) line_plot.add_glyph(source, line) return line_plot
def get_figure(self): fig = figure(match_aspect=True) self.make_point_data(self.graph.visualization_steps[0][1]["points"]) try: fig.circle(x='x_values', y='y_values', size="size", color="color", alpha="alpha",\ legend_group='label', source=self.point_source) except: fig.circle(x='x_values', y='y_values', size="size", color="color", alpha="alpha",\ source=self.point_source) fig.add_layout( LabelSet(x='x_values', y='y_values', text='weight', level='glyph', x_offset="x_offset", y_offset=5, source=self.point_source, render_mode='canvas')) self.make_circle_data() fig.ellipse(x="x_values", y="y_values", width="diameter", height="diameter",\ color="color", fill_color=None, line_width=2, line_alpha = "line_alpha", source=self.circle_source) self.make_segment_data() fig.segment(x0 = "x0", y0="y0", x1="x1", y1="y1", color="black",\ line_alpha = "line_alpha", line_width=2, source=self.segment_source) fig.xaxis.ticker = SingleIntervalTicker(interval=1) fig.yaxis.ticker = SingleIntervalTicker(interval=1) return fig
def make_plot1(df): data = ColumnDataSource( data={ "x": df["Saniye"], "y": df["ECG"], "z": df["AFIB_STATUS"], "r": df[df["Peaks"] == "R"], "q": df[df["Peaks"] == "Q"], "s": df[df["Peaks"] == "S"], "p": df[df["Peaks"] == "QRS_complex_on"], "t": df[df["Peaks"] == "QRS_complex_off"] }) hover_tool1 = HoverTool(tooltips=[("ECG Value", "@y"), ("AFIB Status", "@z"), ("Second", "@x")]) plot1 = figure(tools=[hover_tool1], x_axis_label="Second", y_axis_label="ECG Value", title="Basic ECG Analysis", plot_width=1500, plot_height=500) plot1.xaxis.ticker = SingleIntervalTicker(interval=0.04) plot1.xgrid.grid_line_color = "LightPink" plot1.yaxis.ticker = SingleIntervalTicker(interval=0.04) plot1.ygrid.grid_line_color = "LightPink" plot1.line(x="x", y="y", source=data) for data, name, color in zip([ data.data["r"], data.data["q"], data.data["s"], data.data["p"], data.data["t"] ], ["R", "Q", "S", "QRS_complex_on", "QRS_complex_off"], ["red", "green", "gray", "cyan", "black"]): #df = pd.DataFrame(data) plot1.circle(data["Saniye"], data["ECG"], color=color, alpha=0.8, muted_color=color, muted_alpha=0.1, legend_label=name, size=8) plot1.legend.location = "top_right" plot1.legend.click_policy = "mute" callback2 = CustomJS(args=dict(plot1=plot1), code=""" var a = cb_obj.value; plot1.x_range.start = a[0]; plot1.x_range.end = a[1]; plot1.change.emit(); cb_obj.title = "Interval is " + a[0] + " Second to " + a[1] + " Second" """) slider_widget = RangeSlider(start=df["Saniye"].min(), end=df["Saniye"].max(), step=1, value=(df["Saniye"].min(), df["Saniye"].max()), title="Select Second Interval") slider_widget.js_on_change("value_throttled", callback2) return plot1, slider_widget
def add_axes(plot): xaxis = LinearAxis(SingleIntervalTicker(interval=1), axis_label="Children per woman (total fertility)", **AXIS_FORMATS) yaxis = LinearAxis(SingleIntervalTicker(interval=20), axis_label="Life expectancy at birth (years)", **AXIS_FORMATS) plot.add_layout(xaxis, 'below') plot.add_layout(yaxis, 'left') return plot
def plot(self, plot_width=1200, plot_height=200, scale=36, title='', stats=True): dim = (self.nseq, self.npos) plot = figure(plot_width=plot_width, plot_height=plot_height, x_axis_type=None, x_range=Range1d(0, plot_width / scale, bounds=(-4, 5 + dim[1])), y_range=Range1d( 0, 1.09, ), tools='xpan,reset', toolbar_location=None) title = Label(text=title, x=0, x_offset=20, x_units='screen', y=plot.plot_height, y_offset=-55, y_units='screen', background_fill_color='white', text_font_size='12pt', text_font='monospace') plot.add_layout(title) stats = Label(text='seq=%s pos=%s' % dim, x=plot.plot_width, x_offset=-14, x_units='screen', y=plot.plot_height, y_offset=-46, y_units='screen', background_fill_color='white', text_font_size='10pt', text_align='right', text_font='monospace') if stats: plot.add_layout(stats) ticker = SingleIntervalTicker(interval=5, num_minor_ticks=5) xaxis = LinearAxis(ticker=ticker) plot.add_layout(xaxis, 'below') plot.xaxis.major_label_text_font_style = "bold" plot.xaxis.major_label_text_font_size = "14pt" plot.xaxis.major_label_text_font = "monospace" plot.grid.visible = False plot.yaxis.visible = False plot.xaxis.visible = True img = Image.open(BytesIO(self.print_png_cropped())).convert('RGB') img = np.array(img.convert('RGBA'))[::-1] plot.image_rgba(image=[img], x=.5, y=0, dw=dim[1], dh=1) return show(plot)
def pyramid_plot(self): from bokeh.models import (Plot, DataRange1d, LinearAxis, Grid, Legend, SingleIntervalTicker) from bokeh.models.glyphs import Quad xdr = DataRange1d(sources=[self.source_pyramid.columns("male"), self.source_pyramid.columns("female")]) ydr = DataRange1d(sources=[self.source_pyramid.columns("groups")]) self.plot = Plot(title="Widgets", x_range=xdr, y_range=ydr, plot_width=600, plot_height=600) xaxis = LinearAxis() self.plot.add_layout(xaxis, 'below') yaxis = LinearAxis(ticker=SingleIntervalTicker(interval=5)) self.plot.add_layout(yaxis, 'left') self.plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) self.plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) male_quad = Quad(left="male", right=0, bottom="groups", top="shifted", fill_color="#3B8686") male_quad_glyph = self.plot.add_glyph(self.source_pyramid, male_quad) female_quad = Quad(left=0, right="female", bottom="groups", top="shifted", fill_color="#CFF09E") female_quad_glyph = self.plot.add_glyph(self.source_pyramid, female_quad) self.plot.add_layout(Legend(legends=dict(Male=[male_quad_glyph], Female=[female_quad_glyph])))
def plot_bioact_dist_quad(fasta_fl_path, interval, dataset_name): import bokeh from bokeh.io import show, output_file from bokeh.plotting import figure from bokeh.models import ColumnDataSource, FixedTicker, PrintfTickFormatter from bokeh.io import export_svgs from bokeh.io import export_png from bokeh.models import HoverTool from bokeh.models import SingleIntervalTicker, LinearAxis df_bioactivity = pd.read_csv("{}/comp_targ_affinity.csv".format(comp_tar_training_dataset_path), header=None) sorted_bioactivities_list = sorted(df_bioactivity.iloc[:,2].values) tools = "pan,wheel_zoom,box_zoom,reset" p = figure(tools=tools, plot_width=1400, plot_height=700, title="Distribution of Bioactivity Values - {} Dataset".format(dataset_name), # x_axis_label='Bioacitivity Value (-log(Ki/Kd))', y_axis_label='Number of Bioactivities') p.title.text_font_size = '20pt' p.title.align = "center" # print((sorted_seq_len_list)) arr_hist, edges = np.histogram(sorted_bioactivities_list, bins=list(np.arange(5, 12.0, interval)), range=[5, 12.0]) delays = pd.DataFrame({'arr_length': arr_hist, 'left': edges[:-1], 'right': edges[1:]}) delays['f_interval'] = ['%d - %d' % (left, right) for left, right in zip(delays['left'], delays['right'])] delays['f_count'] = ['%d' % (count) for count in delays['arr_length']] src = ColumnDataSource(delays) print(src.data.keys()) p.quad(bottom=0, left="left", right="right", top="arr_length", source=src, fill_color='red', line_color='black') hover = HoverTool(tooltips=[('Bioactivity Value Range', '@f_interval'), ('Count', '@f_count')]) p.add_tools(hover) p.xgrid.grid_line_color = None # p.x_range.start = 0 p.y_range.start = 0 ticker = SingleIntervalTicker(interval=interval, num_minor_ticks=5) p.xaxis.ticker = ticker #xaxis = LinearAxis(ticker=ticker) #p.xaxis p.xaxis.axis_label = 'Bioacitivity Value (-log(Ki/Kd))' p.xaxis.axis_label_text_font_size = "20pt" p.xaxis.major_label_text_font_size = "10pt" p.yaxis.axis_label = 'Number of Bioactivities' p.yaxis.axis_label_text_font_size = "20pt" p.yaxis.major_label_text_font_size = "15pt" show(p) p.output_backend = "svg" export_svgs(p, filename="../figures/{}_{}_bioact_val_dist.svg".format(dataset_name, interval)) export_png(p, filename="../figures/{}_{}_bioact_val_dist.png".format(dataset_name, interval))
def GP3(doc): from gaussianProcessUtils import drawContour, resample from bokeh.layouts import widgetbox, gridplot from bokeh.models import Slider, Button, SingleIntervalTicker, LinearAxis from bokeh.plotting import figure, ColumnDataSource def resample_wrapper(): numpoints = 1 source.data = resample(numpoints, covariance_slider.value) source3.data = dict(xs=[n + 1 for n in range(numpoints + 1)], ys=[source.data['x1'][0], source.data['x2'][0]]) def update_all(): source2.data = drawContour(covariance_slider.value) resample_wrapper() source = ColumnDataSource(data=dict(x1=[0], x2=[0])) source2 = ColumnDataSource(data=dict(xs=[0], ys=[0])) source3 = ColumnDataSource(data=dict(xs=[0], ys=[0])) plot = figure(y_range=(-3, 3), x_range=(-3, 3), plot_width=400, plot_height=400, x_axis_label='y1', y_axis_label='y2') plot.scatter('x1', 'x2', source=source, line_width=3, line_alpha=0.6) plot.multi_line(xs='xs', ys='ys', line_color='line_color', source=source2) plot2 = figure(y_range=(-3, 3), x_range=(0, 3), plot_width=400, plot_height=400, x_axis_type=None, y_axis_label='y_i value') plot2.line(x='xs', y='ys', source=source3) plot2.scatter('xs', 'ys', source=source3) ticker = SingleIntervalTicker(interval=1, num_minor_ticks=0) xaxis = LinearAxis(ticker=ticker, axis_label='y index') plot2.add_layout(xaxis, 'below') resample_Button = Button(label="Resample") covariance_slider = Slider(start=0.0, end=.99, value=0, step=.01, title="Covariance") resample_Button.on_click(lambda: resample_wrapper()) covariance_slider.on_change('value', lambda attr, old, new: update_all()) controls = [covariance_slider, resample_Button] inputs = widgetbox(*controls, sizing_mode='fixed') l = gridplot([[inputs], [plot, plot2]]) update_all() doc.add_root(l)
def _generate_device_plot(self, device_events): data_source = self._convert_events_to_datasource( device_events['events']) n_rows = device_events['n_rows'] if n_rows == 0: n_rows = 1 elif n_rows == 1: n_rows = 2 name = device_events['name'] plot = figure( title="{}".format(name), plot_height=20 * n_rows + 60, plot_width=1200, tools=self._tools, sizing_mode='stretch_both', # sizing_mode='scale_width', active_scroll='xwheel_zoom') plot.hbar(left='start', right='end', y='height', color='color', height=0.85, source=data_source, hover_fill_alpha=0.5, line_join='round', line_cap='round', hover_line_color='red') plot.x_range = Range1d(0, self._iteration_time, bounds="auto") plot.y_range = Range1d(0, n_rows) plot.yaxis.visible = False plot.ygrid.ticker = SingleIntervalTicker(interval=1) plot.ygrid.grid_line_color = None plot.ygrid.band_fill_alpha = 0.1 plot.ygrid.band_fill_color = "gray" button = Button(label=" Sync", width=20, button_type='primary', disabled=True) button.css_classes = ['xl-hidden'] button.js_on_click( CustomJS(args={ 'me': plot, }, code=self._js_update_ranges)) plot.x_range.js_on_change( 'start', CustomJS(args={ 'button': button, }, code=self._js_on_change_callback)) return plot, WidgetBox(button)
def taskDistributionPlot(glob): taskDistributionAnalytics(glob) yy = [] if glob.pst == "total": myColor = "darkviolet" for item in glob.taskDuration: yy.append( item[0]) # create a list of the data stored in taskDuration else: # "executing" myColor = "navy" for item in glob.taskDuration: yy.append(item[1]) xx = range(0, len( yy)) # set the x-axis to have the same number of points as the y-axis p = figure(plot_height=400, plot_width=800, title=glob.pst, toolbar_location=None, tools="") # make an empty plot p.vbar(x=xx, width=0.95, bottom=0, top=yy, color=myColor) # add a vertical bar glyph p.xaxis.visible = False # This axis contains minor ticks that I cannot remove (1.5, 2.5) which messes up categorical state representation, so hide it. p.yaxis.visible = False # same as above ticker = SingleIntervalTicker(interval=1, num_minor_ticks=0) # create new axis format xaxis = LinearAxis(ticker=ticker) # create the x-axis p.add_layout( xaxis, 'below' ) # add the new x-axis which works properly (no 1.5, 2.5, etc ticks) yaxis = LinearAxis(ticker=ticker) # create the y-axis p.add_layout( yaxis, 'left' ) # add the new y-axis which works properly (no 1.5, 2.5, etc ticks) p.xaxis.axis_label = "task ID" # x-axis label p.xaxis.axis_label_text_font_style = "normal" # non-italicized p.yaxis.axis_label = "time in seconds" # y-axis label: total or current p.yaxis.axis_label_text_font_style = "normal" # non-italicized p.xgrid.grid_line_color = None # no grid color p.xaxis.minor_tick_line_color = None # turn off x-axis minor ticks p.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks return p
def make_bar(color, data): plot = Bar(data, width=200, height=200, palette=[color, COLOR_PRIMARY_DARK], tools='', stacked=True) plot.toolbar_location = None plot.outline_line_color = None plot.min_border = 5 plot.y_range = Range1d(0, 10) # Get chart items legend = plot.select({'type': Legend}) hover = plot.select({'type': HoverTool}) glyphs = plot.select({'type': GlyphRenderer}) xaxis = plot.select({'type': CategoricalAxis}) yaxis = plot.select({'type': LinearAxis}) ygrid = plot.select({'type': Grid}) # Format chart properties plot.toolbar_location = None plot.background_fill = COLOR_PRIMARY plot.border_fill = COLOR_PRIMARY plot.outline_line_color = None plot.min_border_top = 0 # Format legent legend.label_text_color = COLOR_PRIMARY_CONTRAST legend.border_line_color = COLOR_PRIMARY_CONTRAST # Tweak hover hover.tooltips = [('hours', '$y')] hover.point_policy = 'follow_mouse' # Format plots for g in glyphs: g.glyph.fill_alpha = 1 g.glyph.line_color = None # Set xaxis properties xaxis.major_label_text_color = COLOR_PRIMARY_CONTRAST xaxis.major_label_orientation = 0 xaxis.major_label_standoff = 15 xaxis.major_tick_out = None xaxis.major_tick_in = None xaxis.axis_line_color = None # Set yaxis properties yaxis.major_label_text_color = COLOR_PRIMARY_CONTRAST yaxis.major_tick_out = None yaxis.major_tick_in = None yaxis.axis_line_color = None yaxis.ticker = SingleIntervalTicker(interval=3) ygrid.grid_line_color = None return plot
def pyramid(): xdr = DataRange1d(sources=[ source_pyramid.columns("male"), source_pyramid.columns("female") ]) ydr = DataRange1d(sources=[source_pyramid.columns("groups")]) plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=600, plot_height=600) xaxis = LinearAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis(ticker=SingleIntervalTicker(interval=5)) plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) male_quad = Quad(left="male", right=0, bottom="groups", top="shifted", fill_color="#3B8686") male_quad_glyph = plot.add_glyph(source_pyramid, male_quad) female_quad = Quad(left=0, right="female", bottom="groups", top="shifted", fill_color="#CFF09E") female_quad_glyph = plot.add_glyph(source_pyramid, female_quad) plot.add_layout( Legend(legends=[("Male", [male_quad_glyph]), ("Female", [female_quad_glyph])])) return plot
def produce_line(self, df, sort_by=0, ascending=True, label=True): if isinstance(df, dict): df = pd.DataFrame(list(df.items()), columns=['x', 'count']) cols = df.columns df.sort_values(cols[sort_by], inplace=True, ascending=ascending) df[cols[0]] = df[cols[0]].astype(str) source = ColumnDataSource(df) #p.vbar(x=cols[0], top=cols[1], width=0.5, source=source,line_color='white', fill_color=factor_cmap(cols[0], palette=Spectral11, factors=df.index)) TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom" from bokeh.models import SingleIntervalTicker, LinearAxis ticker = SingleIntervalTicker(interval=1) yaxis = LinearAxis(ticker=ticker) p = figure(x_range=list(df[cols[0]]), sizing_mode='stretch_both', tools=TOOLS, toolbar_location='below', title="Counts") p.line(x=cols[0], y=cols[1], source=source, legend=df.name) p.legend.orientation = "horizontal" p.legend.location = "top_right" show(p)
alpha=0.8, legend_label="Sigmoid regression") # p1.line(fakex+yearday[0],yexp,line_color="#ff8888", line_width=4, alpha=0.8, legend_label="Exponentiel regression") p1.line(fakex_forward + yearday[0], y_forward, line_color="#59c25d", line_width=4, alpha=0.4, line_dash=[2, 2], legend_label="Sigmoid regression") # p1.line(fakex_forward+yearday[0],yexp_forward,line_color="#ff8888", line_width=4, alpha=0.4,line_dash=[2,2], legend_label="Exponentiel regression") # p1.line(fakex_forward+yearday[0],midway,line_color="#696969", line_width=4, alpha=0.4,line_dash=[2,2], legend_label="Gennemsnit af regressioner") p1.xaxis.axis_label = 'Dato' p1.yaxis.axis_label = 'Antal' p1.xaxis.ticker = SingleIntervalTicker(interval=dayinterval, num_minor_ticks=dayinterval) p1.y_range = Range1d(0, np.max(hosp) + 125) p1.legend.location = 'top_left' p1.xaxis.major_label_overrides = tickdict save(p1) ##Summary plot of hospitalized p4 = figure(title="Oversigt indlagte - COVID19 - Danmark", tools='', background_fill_color="#fafafa") output_file('stacked.html', title="Oversigt DK") p4.quad(top=hosp, bottom=0, left=yearday - .4, right=yearday + .1,
major_tick_in=None, major_label_text_font_size="10pt", major_label_text_font_style="normal", axis_label_text_font_size="10pt", axis_line_color='#AAAAAA', major_tick_line_color='#AAAAAA', major_label_text_color='#666666', major_tick_line_cap="round", axis_line_cap="round", axis_line_width=1, major_tick_line_width=1, ) xaxis = LinearAxis(ticker=SingleIntervalTicker(interval=1), axis_label="Children per woman (total fertility)", **AXIS_FORMATS) yaxis = LinearAxis(ticker=SingleIntervalTicker(interval=20), axis_label="Life expectancy at birth (years)", **AXIS_FORMATS) plot.add_layout(xaxis, 'below') plot.add_layout(yaxis, 'left') # ### Add the background year text # We add this first so it is below all the other glyphs text_source = ColumnDataSource({'year': ['%s' % years[0]]}) text = Text(x=2, y=35, text='year', text_font_size='150pt', text_color='#EEEEEE') plot.add_glyph(text_source, text) # Add the circle color_mapper = CategoricalColorMapper(palette=Spectral6, factors=regions_list) renderer_source = sources['_%s' % years[0]] circle_glyph = Circle(
def trajectory_analysis_main(traj_files, group_indeces=None, nth_infected=200, data_names=None): '''Main analysis function for the trajectory data ''' if data_names is None: data_names = traj_files dfs_transmit_events = [] dfs_transmit_lags = [] for k, file in enumerate(traj_files): df = pd.read_csv(file) # Select the earliest infections df_early = df.iloc[:nth_infected] # Determine cases infected but never transmitting s_receive = set(df_early['receiver'].array) s_transmit_all = set(df['transmitter'].array) receive_never_transmit = s_receive - s_transmit_all df_index = pd.Index(receive_never_transmit, name='receiver') df_0_count = pd.DataFrame(data=[0] * len(df_index), index=df_index, columns=['day counter']) n_0_count = len(df_0_count) # Determine cases infected and transmitting and how many times df_transmits = df.loc[df['transmitter'].isin(df_early['receiver'])] df_transmits_per_transmitter = df_transmits.groupby(['transmitter']).count() df_transmits_count = df_transmits_per_transmitter.groupby('receiver').count() df_transmits_count.loc[0] = n_0_count # Normalize so empirical frequency of number of infection transmits is obtained total_count = df_transmits_count['day counter'].sum() df_transmits_count['empirical frequency'] = df_transmits_count['day counter'].div(total_count) dfs_transmit_events.append(df_transmits_count.drop(['time since transmitter infected', 'day counter'], axis=1)) # Compute empirical frequency of lag between infection transmits df_transmits_lag = df_transmits.groupby('time since transmitter infected').count() total_count = df_transmits_lag['day counter'].sum() df_transmits_lag['empirical frequency'] = df_transmits_lag['day counter'].div(total_count) dfs_transmit_lags.append(df_transmits_lag.drop(['transmitter', 'receiver', 'day counter'], axis=1)) # Aggregate data groups if not group_indeces is None: dfs_groups1 = [] for group_df in [[dfs_transmit_events[k] for k in group] for group in group_indeces]: df_mean_freq1 = pd.concat(group_df).groupby('receiver').mean() dfs_groups1.append(df_mean_freq1) dfs_groups2 = [] for group_df in [[dfs_transmit_lags[k] for k in group] for group in group_indeces]: df_mean_freq2 = pd.concat(group_df).groupby('time since transmitter infected').mean() dfs_groups2.append(df_mean_freq2) else: raise NotImplementedError('Trajectory analysis without grouper not implemented') source1_to_plot = [ColumnDataSource(df) for df in dfs_groups1] source2_to_plot = [ColumnDataSource(df) for df in dfs_groups2] colors = brewer['PRGn'][max(4, len(source1_to_plot))] if len(source1_to_plot) == 3: colors = [colors[k] for k in [0,1,3]] elif len(source1_to_plot) == 2: colors = [colors[k] for k in [0,3]] if '#f7f7f7' in colors: c_tmp = list(colors) c_tmp[colors.index('#f7f7f7')] = '#999999' colors = tuple(c_tmp) p1 = figure(plot_width=750, plot_height=500, toolbar_location='above') for k, source in enumerate(source1_to_plot): p1.circle(x='receiver', y='empirical frequency', source=source, line_width=3, color=colors[k], line_dash='solid', size=10, legend_label=data_names[k]) p1.line(x='receiver', y='empirical frequency', source=source, line_width=1, color=colors[k], line_dash='dotted') p1.xaxis.axis_label = '# of transmissions to other individuals before recovery' p1.yaxis.axis_label = 'Normalized Frequency' p1.xaxis.ticker = SingleIntervalTicker(interval=1) p1.xaxis.minor_tick_line_color = None p1.legend.location = "top_right" p2 = figure(plot_width=650, plot_height=500, toolbar_location='above') for k, source in enumerate(source2_to_plot): p2.circle(x='time since transmitter infected', y='empirical frequency', source=source, line_width=3, color=colors[k], line_dash='solid', size=10, legend_label=data_names[k]) p2.line(x='time since transmitter infected', y='empirical frequency', source=source, line_width=1, color=colors[k], line_dash='dotted') p2.xaxis.axis_label = 'TUs after infection in which transmitter infects other individual' p2.yaxis.axis_label = 'Normalized Frequency' p2.xaxis.ticker = SingleIntervalTicker(interval=1) p2.xaxis.minor_tick_line_color = None show(column(p1,p2))
for year in years: fertility = fertility_df[year] fertility.name = 'fertility' life = life_expectancy_df[year] life.name = 'life' population = population_df_size[year] population.name = 'population' df = pd.concat([fertility, life, population, region_name], axis=1) df = df.fillna('NaN') sources[year] = ColumnDataSource(df) source = sources[years[0]] plot = figure(x_range=(1, 9), y_range=(20, 100), title='Gapminder Data', plot_height=300) plot.xaxis.ticker = SingleIntervalTicker(interval=1) plot.xaxis.axis_label = "Children per woman (total fertility)" plot.yaxis.ticker = SingleIntervalTicker(interval=20) plot.yaxis.axis_label = "Life expectancy at birth (years)" label = Label(x=1.1, y=18, text=str(years[0]), text_font_size='70pt', text_color='#eeeeee') plot.add_layout(label) color_mapper = CategoricalColorMapper(palette=Spectral6, factors=regions_list) plot.circle( x='fertility', y='life', size='population', source=source, fill_color={'field': 'region', 'transform': color_mapper}, fill_alpha=0.8,
def make_plot2(df): TOOLS = "tap" hover_tool = HoverTool(tooltips=[("Distance", "@dist")]) plot1 = figure(x_axis_label="Second", y_axis_label="ECG Value", title="Basic AFIB Analysis", plot_width=1500, plot_height=500, tools=[TOOLS, hover_tool]) plot1.xaxis.ticker = SingleIntervalTicker(interval=0.04) plot1.xgrid.grid_line_color = "LightPink" plot1.yaxis.ticker = SingleIntervalTicker(interval=0.04) plot1.ygrid.grid_line_color = "LightPink" data3 = ColumnDataSource(data={ "true": df[df["AFIB_STATUS"] == 1], "false": df[df["AFIB_STATUS"] == 0] }) for data, name, color in zip([data3.data["true"], data3.data["false"]], ["Yes", "No"], ["red", "blue"]): plot1.line(data["Saniye"], data["ECG"], color=color, alpha=1, muted_color=color, muted_alpha=0.1, legend_label=name) plot1.legend.location = "top_left" plot1.legend.click_policy = "mute" data = ColumnDataSource( data={ "r": df[df["Peaks"] == "R"], "q": df[df["Peaks"] == "Q"], "s": df[df["Peaks"] == "S"], "p": df[df["Peaks"] == "QRS_complex_on"], "t": df[df["Peaks"] == "QRS_complex_off"], }) for data, name, color in zip([ data.data["r"], data.data["q"], data.data["s"], data.data["p"], data.data["t"] ], ["R", "Q", "S", "QRS_complex_on", "QRS_complex_off"], ["red", "green", "gray", "cyan", "black"]): #df = pd.DataFrame(data) plot1.circle(data["Saniye"], data["ECG"], color=color, alpha=0.8, muted_color=color, muted_alpha=0.1, legend_label=name, size=4) plot1.legend.location = "top_right" plot1.legend.click_policy = "mute" source = ColumnDataSource(data=dict(x=[], y=[], dist=[])) plot1.line(x="x", y="y", source=source) plot1.circle(source=source, x='x', y='y', size=8) callback2 = CustomJS(args=dict(plot1=plot1), code=""" var a = cb_obj.value; plot1.x_range.start = a[0]; plot1.x_range.end = a[1]; plot1.change.emit(); cb_obj.title = "Interval is " + a[0] + " Second to " + a[1] + " Second" """) slider_widget = RangeSlider(start=df["Saniye"].min(), end=df["Saniye"].max(), step=1, value=(df["Saniye"].min(), df["Saniye"].max()), title="Select Second Interval") slider_widget.js_on_change("value", callback2) callback = CustomJS(args=dict(source=source, plot1=plot1, slider_widget=slider_widget), code=""" // the event that triggered the callback is cb_obj: // The event type determines the relevant attributes var data = source.data; var x = data['x'] var y = data['y'] var dist = data['dist'] if(x.length < 1) { x.push(cb_obj.x) y.push(cb_obj.y) dist.push(cb_obj.x - 0) } else if(x.length == 1) { x.push(cb_obj.x) y.push(cb_obj.y) dist.push(cb_obj.x - x[0]) } else { source.data["x"] = [] source.data["y"] = [] } source.change.emit(); """) plot1.js_on_event('tap', callback) callback3 = CustomJS(args=dict(plot1=plot1, slider_widget=slider_widget), code=""" var a = slider_widget.value; plot1.x_range.start = a[0]; plot1.x_range.end = a[1]; plot1.change.emit(); """) plot1.js_on_event(MouseMove, callback3) return plot1, slider_widget
major_tick_line_width=1, ) #xaxis = LinearAxis(SingleIntervalTicker(interval=1))#, axis_label="Children per woman (total fertility)", **AXIS_FORMATS) #yaxis = LinearAxis(SingleIntervalTicker(interval=20))#, axis_label="Life expectancy at birth (years)", **AXIS_FORMATS) xaxis = LinearAxis(axis_label="Children per woman (total fertility)", **AXIS_FORMATS) yaxis = LinearAxis(axis_label="Life expectancy at birth (years)", **AXIS_FORMATS) plot.add_layout(xaxis, 'below') plot.add_layout(yaxis, 'left') # In[ ]: SingleIntervalTicker(interval=1) # In[ ]: # ### Add the background year text # We add this first so it is below all the other glyphs # In[ ]: # Add the year in background (add before circle) text_source = ColumnDataSource({'year': ['%s' % years[0]]}) text = Text(x=2, y=35, text='year', text_font_size='150pt', text_color='#EEEEEE')
new_sch_cases = np.array(sch_data[sc_columns[5]]) tot_tests = np.nan_to_num(np.array(data[columns[9]])).astype(np.int64) dates = pd.to_datetime(data[columns[0]])[2:] dates_num = np.arange(1, len(dates) - 1) tot_deaths = np.nan_to_num(np.array(data['Deaths']).astype(np.int64)) new_deaths = [tot_deaths[x] - tot_deaths[x - 1] for x in range(2, len(tot_deaths))] axis2 = np.nan_to_num(np.array(new_deaths)) # Change column selection here axis3 = np.nan_to_num(np.array(data[columns[9]][2:])) smoothened_y1 = sf(new_cases, window_length=31, polyorder=3) # Creating first figure and setting parameters fig = plt.figure(x_axis_type="datetime", sizing_mode='stretch_both') ticker = SingleIntervalTicker(interval=5, num_minor_ticks=10) fig.xaxis.axis_label = 'Date' fig.y_range = Range1d(start=0, end=max(new_cases) * 1.1) fig.yaxis.axis_label = 'New Daily Cases' # Create second axis and add it to plot fig.extra_y_ranges = {"axis2": Range1d(start=0, end=max(axis2) * 1.1)} fig.add_layout(LinearAxis(y_range_name="axis2", axis_label='Total Deaths'), 'right') source = plt.ColumnDataSource(data={ 'x': dates, 'y1': new_cases, 'y2': axis2, 'y3': smoothened_y1 })
age, EventMortality, sex) source = ColumnDataSource(data=dict(x=agerange, y=mp)) #source = ColumnDataSource(data=dict(x=agerange, y1=np.repeat(0,len(mp)), y2=mp)) source2 = ColumnDataSource( data=dict(x=agerange, y1=np.repeat(0, len(mp2)), y2=mp2)) plot = figure( x_range=(0, 100), y_range=(0, 1), plot_width=700, plot_height=400, title='Life Expectancy (based on United States Life Tables, 2017 CDC/NVSS)' ) plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6) # plot.varea('x', 'y1','y2', source=source2,fill_color='#CFEBE6') plot.varea('x', 'y1', 'y2', source=source2, fill_color='#F4D8D8') plot.xaxis.ticker = SingleIntervalTicker(interval=10) plot.xgrid.ticker = SingleIntervalTicker(interval=10) plot.xaxis.axis_label = "Projected Age" plot.yaxis.ticker = SingleIntervalTicker(interval=0.25) plot.ygrid.ticker = SingleIntervalTicker(interval=0.25) plot.yaxis.axis_label = "Expected Survival rate at projected age" plot.yaxis.formatter = NumeralTickFormatter(format='0 %') label50 = Label(x=5, y=0.5, text=('50% probability still alive at age = ' + str(np.around(MedianAge, decimals=1))), text_font_size='15px', text_color='#0000E6') label75 = Label(x=5, y=0.75, text=('75% probability still alive at age = ' +
sprint["Medal"] = sprint.Medal.map(lambda medal: medal.lower()) sprint["Speed"] = 100.0/sprint.Time sprint["MetersBack"] = 100.0*(1.0 - t0/sprint.Time) sprint["MedalFill"] = sprint.Medal.map(lambda medal: fill_color[medal]) sprint["MedalLine"] = sprint.Medal.map(lambda medal: line_color[medal]) sprint["SelectedName"] = sprint[["Name", "Medal", "Year"]].apply(tuple, axis=1).map(lambda args: selected_name(*args)) source = ColumnDataSource(sprint) xdr =Range1d(start=25, end=-0.5) ydr = DataRange1d(range_padding=2, range_padding_units="absolute") plot = Plot(width=1000, x_range=xdr, y_range=ydr, toolbar_location=None) plot.title.text = "Usain Bolt vs. 116 years of Olympic sprinters" xticker = SingleIntervalTicker(interval=5, num_minor_ticks=0) xaxis = LinearAxis(ticker=xticker, axis_label="Meters behind 2012 Bolt") plot.add_layout(xaxis, "below") xgrid = Grid(dimension=0, ticker=xaxis.ticker) plot.add_layout(xgrid) yticker = SingleIntervalTicker(interval=12, num_minor_ticks=0) yaxis = LinearAxis(ticker=yticker, major_tick_in=-5, major_tick_out=10) plot.add_layout(yaxis, "right") filters = [IndexFilter(list(sprint.query('Medal == "gold" and Year in [1988, 1968, 1936, 1896]').index))] medal = Circle(x="MetersBack", y="Year", size=10, fill_color="MedalFill", line_color="MedalLine", fill_alpha=0.5) medal_renderer = plot.add_glyph(source, medal)
plot_height= 450, title= '7p1 and Cs6s', tooltips= TOOLTIPS, x_axis_label='wavelength(nm)', y_axis_label= 'polarizability', # x_axis_type='linear', # y_axis_type='linear', x_axis_type = None, y_axis_type = None, tools = "pan,wheel_zoom,box_zoom,zoom_in,zoom_out,save,hover,crosshair" ) p.x_range=Range1d(500, 1800) p.y_range=Range1d(-5000, 5000) ticker = SingleIntervalTicker(interval=100, num_minor_ticks=1100) xaxis = LinearAxis(ticker=ticker) # p.xaxis.visible = True xaxis.axis_label = "wavelength (nm)" xaxis.axis_line_width = 1 xaxis.axis_label_text_font_style = "italic" p.add_layout(xaxis, 'below') tickery = SingleIntervalTicker(interval=1000, num_minor_ticks=-5000) yaxis = LinearAxis(ticker=tickery) # Disable scientific notation on yaxis yaxis.formatter.use_scientific = False yaxis.axis_label = "polarizability (a.u.)" yaxis.axis_line_width = 1 yaxis.axis_label_text_font_style = "italic" p.add_layout(yaxis, 'left')
minor_tick_in=None, minor_tick_out=None, major_tick_in=None, major_label_text_font_size="10pt", major_label_text_font_style="normal", axis_label_text_font_size="10pt", axis_line_color='#AAAAAA', major_tick_line_color='#AAAAAA', major_label_text_color='#666666', major_tick_line_cap="round", axis_line_cap="round", axis_line_width=1, major_tick_line_width=1, ) xaxis = LinearAxis(SingleIntervalTicker(interval=1), axis_label="Children per woman (total fertility)", **AXIS_FORMATS) yaxis = LinearAxis(SingleIntervalTicker(interval=20), axis_label="Life expectancy at birth (years)", **AXIS_FORMATS) plot.add_layout(xaxis, 'below') plot.add_layout(yaxis, 'left') # ### Add the background year text # We add this first so it is below all the other glyphs text_source = ColumnDataSource({'year': ['%s' % years[0]]}) text = Text(x=2, y=35, text='year', text_font_size='150pt',
def get_gapminder_plot(): fertility_df, life_expectancy_df, population_df_size, regions_df, years, regions = _process_gapminder_data( ) sources = {} region_color = regions_df['region_color'] region_color.name = 'region_color' for year in years: fertility = fertility_df[year] fertility.name = 'fertility' life = life_expectancy_df[year] life.name = 'life' population = population_df_size[year] population.name = 'population' new_df = pd.concat([fertility, life, population, region_color], axis=1) sources['_' + str(year)] = ColumnDataSource(new_df) dictionary_of_sources = dict( zip([x for x in years], ['_%s' % x for x in years])) js_source_array = str(dictionary_of_sources).replace("'", "") xdr = Range1d(1, 9) ydr = Range1d(20, 100) plot = Plot( x_range=xdr, y_range=ydr, title="", plot_width=800, plot_height=400, outline_line_color=None, toolbar_location=None, responsive=True, ) AXIS_FORMATS = dict( minor_tick_in=None, minor_tick_out=None, major_tick_in=None, major_label_text_font_size="10pt", major_label_text_font_style="normal", axis_label_text_font_size="10pt", axis_line_color='#AAAAAA', major_tick_line_color='#AAAAAA', major_label_text_color='#666666', major_tick_line_cap="round", axis_line_cap="round", axis_line_width=1, major_tick_line_width=1, ) xaxis = LinearAxis(ticker=SingleIntervalTicker(interval=1), axis_label="Children per woman (total fertility)", **AXIS_FORMATS) yaxis = LinearAxis(ticker=SingleIntervalTicker(interval=20), axis_label="Life expectancy at birth (years)", **AXIS_FORMATS) plot.add_layout(xaxis, 'below') plot.add_layout(yaxis, 'left') # ### Add the background year text # We add this first so it is below all the other glyphs text_source = ColumnDataSource({'year': ['%s' % years[0]]}) text = Text(x=2, y=35, text='year', text_font_size='150pt', text_color='#EEEEEE') plot.add_glyph(text_source, text) # Add the circle renderer_source = sources['_%s' % years[0]] circle_glyph = Circle(x='fertility', y='life', size='population', fill_color='region_color', fill_alpha=0.8, line_color='#7c7e71', line_width=0.5, line_alpha=0.5) circle_renderer = plot.add_glyph(renderer_source, circle_glyph) # Add the hover (only against the circle and not other plot elements) tooltips = "@index" plot.add_tools(HoverTool(tooltips=tooltips, renderers=[circle_renderer])) # Add the legend text_x = 7 text_y = 95 for i, region in enumerate(regions): plot.add_glyph( Text(x=text_x, y=text_y, text=[region], text_font_size='10pt', text_color='#666666')) plot.add_glyph( Circle(x=text_x - 0.1, y=text_y + 2, fill_color=Spectral6[i], size=10, line_color=None, fill_alpha=0.8)) text_y = text_y - 5 # Add the slider code = """ var year = slider.get('value'), sources = %s, new_source_data = sources[year].get('data'); renderer_source.set('data', new_source_data); text_source.set('data', {'year': [String(year)]}); """ % js_source_array callback = CustomJS(args=sources, code=code) slider = Slider(start=years[0], end=years[-1], value=1, step=1, title="Year", callback=callback, name='testy') callback.args["renderer_source"] = renderer_source callback.args["slider"] = slider callback.args["text_source"] = text_source # Lay it out return vplot(plot, slider)
def _init_plots(self): """Initialize all plots in the dashboard""" self.exg_plot = figure(y_range=(0.01, self.n_chan + 1 - 0.01), y_axis_label='Voltage', x_axis_label='Time (s)', title="ExG signal", plot_height=250, plot_width=500, y_minor_ticks=int(10), tools=[ResetTool()], active_scroll=None, active_drag=None, active_inspect=None, active_tap=None, sizing_mode="scale_width") self.mag_plot = figure(y_axis_label='Mag [mgauss/LSB]', x_axis_label='Time (s)', plot_height=100, plot_width=500, tools=[ResetTool()], active_scroll=None, active_drag=None, active_inspect=None, active_tap=None, sizing_mode="scale_width") self.acc_plot = figure(y_axis_label='Acc [mg/LSB]', plot_height=75, plot_width=500, tools=[ResetTool()], active_scroll=None, active_drag=None, active_inspect=None, active_tap=None, sizing_mode="scale_width") self.acc_plot.xaxis.visible = False self.gyro_plot = figure(y_axis_label='Gyro [mdps/LSB]', plot_height=75, plot_width=500, tools=[ResetTool()], active_scroll=None, active_drag=None, active_inspect=None, active_tap=None, sizing_mode="scale_width") self.gyro_plot.xaxis.visible = False self.fft_plot = figure(y_axis_label='Amplitude (uV)', x_axis_label='Frequency (Hz)', title="FFT", x_range=(0, 70), plot_height=250, plot_width=500, y_axis_type="log", tools=[BoxZoomTool(), ResetTool()], active_scroll=None, active_drag=None, active_tap=None, sizing_mode="scale_width") self.imp_plot = self._init_imp_plot() # Set yaxis properties self.exg_plot.yaxis.ticker = SingleIntervalTicker(interval=1, num_minor_ticks=0) # Initial plot line for i in range(self.n_chan): self.exg_plot.line(x='t', y=self.chan_key_list[i], source=self._exg_source_ds, line_width=1.0, alpha=.9, line_color="#42C4F7") self.fft_plot.line(x='f', y=self.chan_key_list[i], source=self.fft_source, legend_label=self.chan_key_list[i] + " ", line_width=1.5, alpha=.9, line_color=FFT_COLORS[i]) self.fft_plot.yaxis.axis_label_text_font_style = 'normal' self.exg_plot.line(x='t', y='marker', source=self._marker_source, line_width=1, alpha=.8, line_color='#7AB904', line_dash="4 4") for i in range(3): self.acc_plot.line(x='t', y=ORN_LIST[i], source=self._orn_source, legend_label=ORN_LIST[i] + " ", line_width=1.5, line_color=LINE_COLORS[i], alpha=.9) self.gyro_plot.line(x='t', y=ORN_LIST[i + 3], source=self._orn_source, legend_label=ORN_LIST[i + 3] + " ", line_width=1.5, line_color=LINE_COLORS[i], alpha=.9) self.mag_plot.line(x='t', y=ORN_LIST[i + 6], source=self._orn_source, legend_label=ORN_LIST[i + 6] + " ", line_width=1.5, line_color=LINE_COLORS[i], alpha=.9) # Set x_range self.plot_list = [self.exg_plot, self.acc_plot, self.gyro_plot, self.mag_plot] self._set_t_range(WIN_LENGTH) # Set the formatting of yaxis ticks' labels self.exg_plot.yaxis.major_label_overrides = dict(zip(range(1, self.n_chan + 1), self.chan_key_list)) for plot in self.plot_list: plot.toolbar.autohide = True plot.yaxis.axis_label_text_font_style = 'normal' if len(plot.legend) != 0: plot.legend.location = "bottom_left" plot.legend.orientation = "horizontal" plot.legend.padding = 2