def histogram_plot(states, height, width, data_top, data_source, n_ticks, n_minor_ticks=0, fill_color=None): '''Create a bokeh histogram using quad shapes''' from bokeh.plotting import Figure # Create histogram object hist_obj = Figure(plot_height=height, plot_width=width, title="", toolbar_location=None) # Data top is string of var name from data_source fill_color = '#f0f5f5' if fill_color == None else fill_color hist_obj.quad(top=data_top, bottom=0, source=data_source, left="left", right="right", fill_color=fill_color, line_color='black') # set number of major and minor ticks hist_obj.xaxis[0].ticker.desired_num_ticks = n_ticks hist_obj.xaxis[0].ticker.num_minor_ticks = n_minor_ticks hist_obj.y_range = Range1d(0, 1) hist_obj.x_range = Range1d(states[0] - 0.5, states[-1] + 0.5) return hist_obj
def plt(self): source_normal = ColumnDataSource(data=get_normal(0, 1, 10000)) plot_normal = Figure(plot_width=450, plot_height=450, x_range=(-6, 6), title='Normal') plot_normal.quad(top='hist', bottom=0, left='left_edges', right='right_edges', source=source_normal, fill_color="navy") def update_plot_normal(attrname, old, new): source_normal.data = get_normal(mu_slider.value, sigma_slider.value, 10000) mu_slider = Slider(start=-5, end=5, value=0, step=0.2, title='Mean') mu_slider.on_change('value', update_plot_normal) sigma_slider = Slider(start=0.1, end=5, value=1, step=0.2, title='Std_Dev') sigma_slider.on_change('value', update_plot_normal) layout = row(plot_normal, column(mu_slider, sigma_slider))
def landscape_plot(landscape, states, timesteps, height, width, patch_colors): '''Plot fitness landscape''' from bokeh.plotting import Figure # Append extra state and timestep for index bounds of quad objects states = numpy.append(states, states[-1]+1) timesteps = numpy.append(timesteps, timesteps[-1]+1) # Create points for each cell of grid tops = list() bottoms = list() lefts = list() rights = list() for top, bottom in zip(states[1:], states[:-1]): for left, right in zip(timesteps[:-1], timesteps[1:]): tops.append(top) bottoms.append(bottom) lefts.append(left) rights.append(right) # Create array of color values corresponding to each cell's assoc. patch grid_colors = list() for i in range(len(tops)): idx = (landscape['state']==bottoms[i]) & (landscape['t']==lefts[i]) patch = int(landscape[idx]['patch']) grid_colors.append(patch_colors[patch]) # Create landscape object grid_obj = Figure(plot_height=height, plot_width=width, title="", toolbar_location=None) grid_obj.quad(top=tops, bottom=bottoms, left=lefts, right=rights, line_color='black', fill_color=grid_colors) return grid_obj
def make_precipitation_plot(source): plot = Figure(x_axis_type="datetime", plot_width=1000, plot_height=125, min_border_left=50, min_border_right=50, min_border_top=0, min_border_bottom=0, toolbar_location=None) plot.title = None plot.quad(top='actual_precipitation', bottom=0, left='left', right='right', color=Greens4[1], source=source) # fixed attributes plot.border_fill_color = "whitesmoke" plot.yaxis.axis_label = "Precipitation (in)" plot.axis.major_label_text_font_size = "8pt" plot.axis.axis_label_text_font_size = "8pt" plot.axis.axis_label_text_font_style = "bold" plot.x_range = DataRange1d(range_padding=0.0, bounds=None) plot.y_range = DataRange1d(range_padding=0.0, bounds=None) plot.grid.grid_line_alpha = 0.3 plot.grid[0].ticker.desired_num_ticks = 12 return plot
def __plot_histogram(self): plot = Figure(plot_height=500, plot_width=300) plot.title.text = 'Histogram' hist_data = self.calc_histogram_data(self.__values) plot.toolbar.logo = None plot.quad(top='hist', bottom=0, left='edges_left', right='edges_right', source=hist_data, fill_color="#036564", line_color="#033649") return plot
def Main(): parser = argparse.ArgumentParser() parser.add_argument("-st", dest="stationId", nargs='*') parser.add_argument("-ct", dest="cityName", nargs='*') parser.add_argument("-pr", dest="percentage", nargs='*') parser.add_argument("-tc1", dest="taskColor1", nargs='*') args = parser.parse_args() for i in range(len(args.stationId)): Data, Date, Max, Min = prepareCSVData(args.cityName[i]) plotDate = Data['right'] source = ColumnDataSource(data=Data) AverageTemp = [] for index in range(len(Min)): Average = (Min[index] + Max[index]) / 2 AverageTemp.append(Average) plot_graph = Figure(x_axis_type="datetime", plot_width=1000, title="2016 Daily Growing Degree Days- " + args.cityName[i], toolbar_location=None) color = "#ADD8E6" for j in range(len(args.percentage)): minPer, MaxPer = getComputePercentage(Min, Max, args.percentage[j]) plot_graph.quad(top=MaxPer, bottom=minPer, left='left', right='right', source=source, color=color, legend="percentile " + str(args.percentage[j]) + "-" + str(100 - int(args.percentage[j]))) color = "#D2B48C" plot_graph.circle(Max, Min, alpha=0.9, color="#0000FF", fill_alpha=0.2, size=10, source=source, legend='2016') plot_graph.line(plotDate, AverageTemp, source=source, line_color='Red', line_width=0.5, legend='Average') plot_graph.xaxis.axis_label = "MONTHS" plot_graph.yaxis.axis_label = "Daily Accumulation Celcius" plot_graph.grid[0].ticker.desired_num_ticks = 12 output_file("./plots/secTask-1" + args.cityName[i] + ".html", title="2016 Daily Growing Degree Days-(" + args.cityName[i] + ")") save(plot_graph)
def make_plot(source, AverageTemp, Parcentile_5_Min, Parcentile_5_Max, Parcentile_25_Min, Parcentile_25_Max, MinTemp, MaxTemp, plotDate, cityName): plot = Figure(title='Optional Task # 1 : Growing Degree-day for ' + cityName, x_axis_type="datetime", plot_width=1000, title_text_font_size='12pt', tools="", toolbar_location=None) colors = Blues4[0:3] plot.circle(MaxTemp, MinTemp, alpha=0.9, color="#66ff33", fill_alpha=0.2, size=10, source=source, legend='2015') plot.quad(top=Parcentile_5_Max, bottom=Parcentile_5_Min, left='left', right='right', source=source, color="#e67300", legend="Percentile 5-95") plot.quad(top=Parcentile_25_Max, bottom=Parcentile_25_Min, left='left', right='right', source=source, color="#66ccff", legend="percentile 25-75") plot.line(plotDate, AverageTemp, source=source, line_color='Red', line_width=0.75, legend='AverageTemp') plot.border_fill_color = "whitesmoke" plot.xaxis.axis_label = "Months" plot.yaxis.axis_label = "Temperature (C)" plot.axis.major_label_text_font_size = "10pt" plot.axis.axis_label_text_font_size = "12pt" plot.axis.axis_label_text_font_style = "bold" plot.x_range = DataRange1d(range_padding=0.0, bounds=None) plot.grid.grid_line_alpha = 0.3 plot.grid[0].ticker.desired_num_ticks = 12 return plot
def hist_viz( df: pd.DataFrame, miss_pct: float, col: str, yscale: str, plot_width: int, plot_height: int, show_yaxis: bool, ) -> Figure: """ Render a histogram """ # pylint: disable=too-many-arguments title = f"{col} ({miss_pct}% missing)" if miss_pct > 0 else f"{col}" tooltips = [ ("Bin", "@intervals"), ("Frequency", "@freq"), ("Percent", "@pct{0.2f}%"), ] fig = Figure( plot_width=plot_width, plot_height=plot_height, toolbar_location=None, title=title, tools=[], y_axis_type=yscale, ) bottom = 0 if yscale == "linear" or df.empty else df["freq"].min() / 2 fig.quad( source=df, left="left", right="right", bottom=bottom, alpha=0.5, top="freq", fill_color="#6baed6", ) hover = HoverTool( tooltips=tooltips, mode="vline", ) fig.add_tools(hover) tweak_figure(fig, "hist", show_yaxis) fig.yaxis.axis_label = "Frequency" if not df.empty: _format_axis(fig, df.iloc[0]["left"], df.iloc[-1]["right"], "x") if show_yaxis and yscale == "linear": _format_axis(fig, 0, df["freq"].max(), "y") return fig
def createPlot(df, boundaryDF): p = Figure(plot_height=900, plot_width=PLOT_WIDTH, title="", y_range=[], title_text_font_size=TITLE_FONT_SIZE) p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None quad = p.quad( top="top", bottom="bottom", left="left", right="right", source=blockSource, fill_color="grey", hover_fill_color="firebrick", fill_alpha=0.05, hover_alpha=0.3, line_color=None, hover_line_color="white", ) p.multi_line(xs="xs", ys="ys", source=blockSource, color="black", line_width=2, line_alpha=0.4, line_dash="dotted") p.multi_line(xs="xs", ys="ys", source=source, color="color", line_width="width", line_alpha="line_alpha") p.add_tools( HoverTool( tooltips=[("chromosome", "@chromosome"), ("exon", "@exon"), ("start", "@start"), ("end", "@end")], renderers=[quad], ) ) return p
class ColorBar(object): def __init__(self): self.map_colorbar = Figure(tools="", toolbar_location=None, min_border=0, min_border_right=0, plot_width=80, plot_height=650, x_range=(0., 1.), y_range=conso_bounds) self.map_colorbar.xaxis.visible = None self.map_colorbar.grid.grid_line_color = None colorbar_ys = np.linspace(conso_bounds[0], conso_bounds[1], 12) colorbar_colors = scales_to_hex(np.linspace(0., 1., 11)) self.map_colorbar.quad(bottom=colorbar_ys[:-1], top=colorbar_ys[1:], left=0., right=1., fill_color=colorbar_colors, line_color=None, alpha=0.9) def get_plot(self): return self.map_colorbar
def scoredistplots(preds): """Score distribution plots""" from bokeh.models import Range1d,GridPlot from bokeh.plotting import Figure plots=[] for p in preds: pred=preds[p] key=pred.scorekey data = pred.data[key] hist, edges = np.histogram(data, density=True, bins=30) p = Figure(title=p,plot_height=250,tools='') p.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:], fill_color="#036564", line_color="#033649") p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None plots.append(p) plot = GridPlot(children=[plots],title='test') js,html = embedPlot(plot) return html
def hist_kde_viz( df: pd.DataFrame, pts_rng: np.ndarray, pdf: np.ndarray, col: str, yscale: str, plot_width: int, plot_height: int, ) -> Panel: """ Render histogram with overlayed kde """ # pylint: disable=too-many-arguments fig = Figure( plot_width=plot_width, plot_height=plot_height, title=f"{col}", tools=[], toolbar_location=None, y_axis_type=yscale, ) bottom = 0 if yscale == "linear" or df.empty else df["freq"].min() / 2 hist = fig.quad( source=df, left="left", right="right", bottom=bottom, alpha=0.5, top="freq", fill_color="#6baed6", ) hover_hist = HoverTool( renderers=[hist], tooltips=[("Bin", "@intervals"), ("Density", "@freq")], mode="vline", ) line = fig.line( # pylint: disable=too-many-function-args pts_rng, pdf, line_color="#9467bd", line_width=2, alpha=0.5) hover_dist = HoverTool(renderers=[line], tooltips=[("x", "@x"), ("y", "@y")]) fig.add_tools(hover_hist) fig.add_tools(hover_dist) tweak_figure(fig, "kde") fig.yaxis.axis_label = "Density" fig.xaxis.axis_label = col _format_axis(fig, df.iloc[0]["left"], df.iloc[-1]["right"], "x") if yscale == "linear": _format_axis(fig, 0, df["freq"].max(), "y") return Panel(child=fig, title="KDE plot")
def make_plot(source,AverageTemp,Parcentile_5_Min,Parcentile_5_Max,Parcentile_25_Min,Parcentile_25_Max,MinTemp,MaxTemp,plotDate,cityName): plot = Figure(title='Optional Task # 1 : Growing Degree-day for '+cityName, x_axis_type="datetime", plot_width=1000, title_text_font_size='12pt', tools="", toolbar_location=None) colors = Blues4[0:3] plot.circle(MaxTemp,MinTemp, alpha=0.9, color="#66ff33", fill_alpha=0.2, size=10,source=source,legend ='2015') plot.quad(top=Parcentile_5_Max, bottom=Parcentile_5_Min, left='left',right='right', source=source,color="#e67300", legend="Percentile 5-95") plot.quad(top=Parcentile_25_Max, bottom=Parcentile_25_Min,left='left',right='right', source=source,color="#66ccff",legend="percentile 25-75") plot.line(plotDate,AverageTemp,source=source,line_color='Red', line_width=0.75, legend='AverageTemp') plot.border_fill_color = "whitesmoke" plot.xaxis.axis_label = "Months" plot.yaxis.axis_label = "Temperature (C)" plot.axis.major_label_text_font_size = "10pt" plot.axis.axis_label_text_font_size = "12pt" plot.axis.axis_label_text_font_style = "bold" plot.x_range = DataRange1d(range_padding=0.0, bounds=None) plot.grid.grid_line_alpha = 0.3 plot.grid[0].ticker.desired_num_ticks = 12 return plot
def landscape_plot(landscape, states, timesteps, height, width, patch_colors): '''Plot fitness landscape''' from bokeh.plotting import Figure # Append extra state and timestep for index bounds of quad objects states = numpy.append(states, states[-1] + 1) timesteps = numpy.append(timesteps, timesteps[-1] + 1) # Create points for each cell of grid tops = list() bottoms = list() lefts = list() rights = list() for top, bottom in zip(states[1:], states[:-1]): for left, right in zip(timesteps[:-1], timesteps[1:]): tops.append(top) bottoms.append(bottom) lefts.append(left) rights.append(right) # Create array of color values corresponding to each cell's assoc. patch grid_colors = list() for i in range(len(tops)): idx = (landscape['state'] == bottoms[i]) & (landscape['t'] == lefts[i]) patch = int(landscape[idx]['patch']) grid_colors.append(patch_colors[patch]) # Create landscape object grid_obj = Figure(plot_height=height, plot_width=width, title="", toolbar_location=None) grid_obj.quad(top=tops, bottom=bottoms, left=lefts, right=rights, line_color='black', fill_color=grid_colors) return grid_obj
def histogram_plot(states, height, width, data_top, data_source, n_ticks, n_minor_ticks=0, fill_color=None): '''Create a bokeh histogram using quad shapes''' from bokeh.plotting import Figure # Create histogram object hist_obj = Figure(plot_height=height, plot_width=width, title="", toolbar_location=None) # Data top is string of var name from data_source fill_color = '#f0f5f5' if fill_color==None else fill_color hist_obj.quad(top=data_top, bottom=0, source=data_source, left="left", right="right", fill_color=fill_color, line_color='black') # set number of major and minor ticks hist_obj.xaxis[0].ticker.desired_num_ticks = n_ticks hist_obj.xaxis[0].ticker.num_minor_ticks = n_minor_ticks hist_obj.y_range = Range1d(0, 1) hist_obj.x_range = Range1d(states[0]-0.5, states[-1]+0.5) return hist_obj
def make_plot(source, title): print("make plot") plot = Figure(x_axis_type="datetime", plot_width=1000, tools="", toolbar_location=None) plot.title = title colors = Blues4[0:3] plot.quad(top='record_max_temp', bottom='record_min_temp', left='left', right='right', color=colors[2], source=source, legend="Record") plot.quad(top='average_max_temp', bottom='average_min_temp', left='left', right='right', color=colors[1], source=source, legend="Average") plot.quad(top='actual_max_temp', bottom='actual_min_temp', left='left', right='right', color=colors[0], alpha=0.5, line_color="black", source=source, legend="Actual") # fixed attributes plot.border_fill_color = "whitesmoke" plot.xaxis.axis_label = None plot.yaxis.axis_label = "Temperature (F)" plot.axis.major_label_text_font_size = "8pt" plot.axis.axis_label_text_font_size = "8pt" plot.axis.axis_label_text_font_style = "bold" plot.x_range = DataRange1d(range_padding=0.0, bounds=None) plot.grid.grid_line_alpha = 0.3 plot.grid[0].ticker.desired_num_ticks = 12 return plot
def make_plot(source, title): plot = Figure(x_axis_type="datetime", plot_width=1000, tools="", toolbar_location=None) plot.title = title colors = Blues4[0:3] plot.quad(top='record_max_temp', bottom='record_min_temp', left='left', right='right', color=colors[2], source=source, legend="Record") plot.quad(top='average_max_temp', bottom='average_min_temp', left='left', right='right', color=colors[1], source=source, legend="Average") plot.quad(top='actual_max_temp', bottom='actual_min_temp', left='left', right='right', color=colors[0], alpha=0.5, line_color="black", source=source, legend="Actual") # fixed attributes plot.border_fill_color = "whitesmoke" plot.xaxis.axis_label = None plot.yaxis.axis_label = "Temperature (F)" plot.axis.major_label_text_font_size = "8pt" plot.axis.axis_label_text_font_size = "8pt" plot.axis.axis_label_text_font_style = "bold" plot.x_range = DataRange1d(range_padding=0.0, bounds=None) plot.grid.grid_line_alpha = 0.3 plot.grid[0].ticker.desired_num_ticks = 12 return plot
class Plot2d: def __init__(self, x_range=None, y_range=None, x_label="", y_label="", tooltip=None, title="", width=600, height=400, yscale="auto", font_size="1vw", hover_mode="mouse"): hover = HoverTool(tooltips=tooltip, mode=hover_mode) if y_range == None: self.plot = Figure( tools=[hover, "pan,wheel_zoom,box_zoom,reset,crosshair,tap"], plot_width=width, active_drag="box_zoom", plot_height=height, background_fill_color="white", x_axis_type="auto", y_axis_type=yscale) else: self.plot = Figure( tools=[hover, "pan,wheel_zoom,box_zoom,reset,crosshair,tap"], plot_width=width, active_drag="box_zoom", plot_height=height, background_fill_color="white", x_axis_type="auto", y_axis_type=yscale, y_range=y_range, x_range=x_range) self.plot.xaxis.axis_label = x_label self.plot.yaxis.axis_label = y_label self.plot.xaxis.major_label_text_font_size = font_size self.plot.yaxis.major_label_text_font_size = font_size self.plot.xaxis.axis_label_text_font_size = font_size self.plot.yaxis.axis_label_text_font_size = font_size self.plot.legend.label_text_font_size = font_size self.plot.title.text_font_size = font_size self.plot.title.text = title def vbar(self, source, y="y", x="x", line_width=0.01): self.plot.vbar(top=y, x=x, width=0.8, source=source, fill_color="dodgerblue", line_color="black", line_width=line_width, alpha=0.8, hover_fill_color='red', hover_line_color='red', hover_alpha=0.8) return self.plot def quad(self, source, top, bottom='bottom', left='left', right='right', name='data', line_width=0.1): self.plot.quad(top=top, bottom=bottom, left=left, right=right, name=name, source=source, fill_color="dodgerblue", line_color="black", line_width=line_width, alpha=0.8, hover_fill_color='red', hover_line_color='red', hover_alpha=0.8) return self.plot def line(self, source, x='x', y='y', color="black", line_width=1.5, line_alpha=0.9): self.plot.line(x=x, y=y, source=source, color=color, line_width=line_width, line_alpha=line_alpha) return self def circle(self, source, x='x', y='y', color="blue", size=8, line_color='black', alpha=0.7, hover_color="blue", hover_alpha=1, hover_line_color='red', radius=0.0165, fill_color='lightgray', line_width=0.3, hover_fill_color=None): self.plot.circle( x=x, y=y, source=source, color=color, size=size, line_color=line_color, alpha=alpha, hover_color=hover_color, hover_alpha=hover_alpha, hover_line_color=hover_line_color, fill_color=fill_color, hover_fill_color=hover_fill_color, ) return self def set_colorbar(self, z_value): ''' Setup for colorbar ''' dz = z_value # removing NaN in ranges dz_valid = [x if x > -999 else np.nan for x in dz] dzmax, dzmin = np.nanmax(dz_valid), np.nanmin(dz_valid) if np.log10(dzmax) > 4 or np.log10(dzmin) < -3: ztext = ['{:4.2e}'.format(i) for i in dz_valid] cbarformat = "%2.1e" elif np.log10(dzmin) > 0: ztext = ['{:5.2f}'.format(i) for i in dz_valid] cbarformat = "%4.2f" else: ztext = ['{:6.2f}'.format(i) for i in dz_valid] cbarformat = "%5.2f" return ztext, cbarformat def colorbar(self, mapper, title='(Val - Ref)'): formatter = PrintfTickFormatter(format="%4.2f") color_bar = ColorBar(color_mapper=mapper, label_standoff=16, title=title, major_label_text_font_style='bold', padding=26, major_label_text_align='left', major_label_text_font_size="10pt", formatter=formatter, title_text_baseline='alphabetic', location=(0, 0)) self.plot.add_layout(color_bar, 'right') return self def wedge(self, source, field=None, x="x", y="y", mapper=None, radius=0.0165, colorbar_title='counts'): if mapper: self.plot = self.circle( source, y=y, x=x, radius=radius, fill_color={ 'field': field, 'transform': mapper }, line_color='black', line_width=0.3, ).circle(source, y=y, x=x, radius=radius + 0.005, fill_color=None, line_color=None, line_width=3, hover_fill_color={ 'field': field, 'transform': mapper }, hover_line_color='red').colorbar( mapper, title=colorbar_title).plot elif field: self.plot = self.circle( source, y=y, x=x, radius=radius, hover_fill_color='lightgrey', fill_color={ 'field': 'color' }, line_color='black', line_width=0.3, ).plot else: self.plot = self.circle( source, y=y, x=x, radius=radius, hover_fill_color='lightgrey', fill_color='darkgrey', line_color='black', line_width=0.3, ).plot return self def segment(self, source, x0='segx0', x1='segx1', y0='segy0', y1='segy1', line_width=2, line_color='#1e90ff'): seg = Segment(x0=x0, x1=x1, y0=y0, y1=y1, line_width=line_width, line_color=line_color) self.plot.add_glyph(source, seg) self.plot.yaxis.ticker = FixedTicker(ticks=[0, 1]) self.plot.yaxis.major_label_overrides = {'0': 'bad', '1': 'good'} return self
DYNAMIC_EVENTS = {"Acceleration Score": "Accel Best Time", "Skid Pad Score": "Skid Pad Best Time", "Autocross Score": "AutoX Best Time", "Efficiency Score": "Endurance Adjusted Time", "Endurance Score": "Endurance Adjusted Time"} # Read in the FSAEM data compdata = pd.read_excel('FSAEM_summarized_results.xlsx') source = ColumnDataSource(data=dict()) # Initialize the plot plot = Figure(plot_width=800, plot_height=500, toolbar_location='right', tools="pan,wheel_zoom,box_zoom,reset,resize") freq_bars = plot.quad(top='hist', bottom=0, left='left_edge', right='right_edge', source=source, fill_color=YlOrBr3[0], line_color='#000000') plot.xaxis.axis_label = "Total Score" plot.xaxis.axis_line_color = None plot.xaxis.minor_tick_line_color = None plot.yaxis.axis_label = "Frequency" plot.yaxis.axis_line_color = None plot.yaxis.major_tick_line_color = None plot.yaxis.minor_tick_line_color = None plot.xgrid.grid_line_color = None plot.ygrid.grid_line_color = None plot.outline_line_color = None
'left': edges_low[:-1], 'right': edges_low[1:] }) phi = Figure(title='NBINSHI', tools=[hover, "pan,wheel_zoom,box_zoom,reset"], y_axis_label='Frequency', x_axis_label='COUNTBINS', background_fill_color="white") phi.quad(top='hist', bottom='bottom', left='left', right='right', source=source_hi, fill_color="dodgerblue", line_color="black", alpha=0.8, hover_fill_color='blue', hover_line_color='black', hover_alpha=0.8) pmed = Figure(title='NBINSMED', tools=[hover2, "pan,wheel_zoom,box_zoom,reset"], y_axis_label='Frequency', x_axis_label='COUNTBINS', background_fill_color="white") pmed.quad(top='hist', bottom='bottom', left='left',
selected_year = Slider(title="Year", start=1900, end=current_year, value=2008, step=1) station_IDs_str = TextInput(title="Station ID", value='6551') # Create Figure and Plot hover = HoverTool(tooltips=[("Date", "@date_str"), ("Station ID", "@station_id")]) p = Figure(x_axis_type="datetime", plot_width=800, tools=[hover]) p.quad(top='max_t', bottom='min_t', left='timel', right='timer', source=source, alpha=0.5, color='RoyalBlue', line_color="black", line_alpha=0.5, legend='Min/Max') p.line(x='time', y='mean_t', source=source, color='red', line_width=1.5, alpha=0.8, legend='Average') p.x_range = DataRange1d(range_padding=0, bounds=None) p.yaxis.axis_label = "Temperature (C)" p.xaxis.axis_label = 'Month'
def plot(width, height): ###################################################################################################################### source_normal = ColumnDataSource(data = get_normal(0,1,10000)) plot_normal = Figure(plot_width = width, plot_height = height, x_range = (-6,6), title = 'Normal') plot_normal.quad(top='hist', bottom=0, left='left_edges', right='right_edges', source= source_normal, fill_color="navy") def update_plot_normal(attrname, old , new): source_normal.data = get_normal(mu_slider.value, sigma_slider.value, 100000) mu_slider = Slider(start = -5, end = 5, value = 0, step = 0.2, title = 'Mean') mu_slider.on_change('value', update_plot_normal) sigma_slider = Slider(start = 0.1, end = 5, value = 1, step = 0.2, title = 'Std_Dev') sigma_slider.on_change('value', update_plot_normal) ###################################################################################################################### source_weibull = ColumnDataSource(data = get_weibull(1.5, 1, 10000)) plot_weibull = Figure(plot_width = width, plot_height = height, x_range = (0,6), title = 'Weibull') plot_weibull.quad(top='hist', bottom=0, left='left_edges', right='right_edges', source= source_weibull, fill_color="navy") def update_plot_weibull(attrname, old , new): source_weibull.data = get_weibull(shape_slider.value,lambda_slider.value,100000) shape_slider = Slider(start = 0.4, end = 5, value = 1.5, step = 0.1, title = 'Shape a') shape_slider.on_change('value', update_plot_weibull) lambda_slider = Slider(start = 0.5, end = 3, value = 1, step = 0.5, title = 'Lambda') lambda_slider.on_change('value', update_plot_weibull) ###################################################################################################################### source_lognormal = ColumnDataSource(data = get_lognormal(0.9, 0.16, 10000)) plot_lognormal = Figure(plot_width = width, plot_height = height, title = 'Lognormal', y_range=(0,2), x_range = (0,10)) plot_lognormal.quad(top='hist', bottom=0, left='left_edges', right='right_edges', source= source_lognormal, fill_color="navy") def update_plot_lognormal(attrname, old , new): source_lognormal.data = get_lognormal(mean_slider_lognormal.value, sigma_slider_lognormal.value,100000) mean_slider_lognormal = Slider(start = 0, end = 5, value =0.9, step = 0.1, title = 'Mean') mean_slider_lognormal.on_change('value', update_plot_lognormal) sigma_slider_lognormal = Slider(start = 0.01, end = 1, value = 0.16, step = 0.01, title = 'Std_dev') sigma_slider_lognormal.on_change('value', update_plot_lognormal) ###################################################################################################################### source_exponential = ColumnDataSource(data = get_exponential(3, 1000)) plot_exponential = Figure(plot_width = width, plot_height = height, title = 'Exponential', x_range=(0,50), y_range =(0,1) ) plot_exponential.quad(top='hist', bottom=0, left='left_edges', right='right_edges', source= source_exponential, fill_color="green") def update_plot_exponential(attrname, old , new): source_exponential.data = get_exponential(scale_slider_exponential.value, 10000) scale_slider_exponential = Slider(start = 0.1, end = 10, value = 3, step = 0.1, title = 'Scale') scale_slider_exponential.on_change('value', update_plot_exponential) layout1 = column(plot_normal, column(mu_slider, sigma_slider)) layout2 = column(plot_weibull, column(shape_slider, lambda_slider)) layout3 = column(plot_lognormal, column(mean_slider_lognormal, sigma_slider_lognormal)) layout4 = column(plot_exponential, scale_slider_exponential) top = row(layout1, layout2) bottom = row(layout3, layout4) return (row(top, bottom))
def plot_dispersion_bokeh(filename, period_array, curve_data_array, boundary_data, style_parameter): ''' Plot dispersion maps and curves using bokeh Input: filename is the filename of the resulting html file period_array is a list of period curve_data_array is a list of dispersion curves boundary_data is a list of boundaries style_parameter contains plotting parameters Output: None ''' xlabel_fontsize = style_parameter['xlabel_fontsize'] # ============================== # prepare data map_data_all_slices_velocity = [] map_data_all_slices_period = [] map_data_all_slices_color = [] colorbar_data_all_left = [] colorbar_data_all_right = [] nperiod = len(period_array) ncurve = len(curve_data_array) ncolor = len(palette) palette_r = palette[::-1] colorbar_top = [0.1 for i in range(ncolor)] colorbar_bottom = [0 for i in range(ncolor)] for iperiod in range(nperiod): one_slice_lat_list = [] one_slice_lon_list = [] one_slice_vel_list = [] map_period = period_array[iperiod] for icurve in range(ncurve): acurve = curve_data_array[icurve] curve_lat = acurve['latitude'] curve_lon = acurve['longitude'] curve_vel = acurve['velocity'] curve_period = acurve['period'] one_slice_lat_list.append(curve_lat) one_slice_lon_list.append(curve_lon) if map_period in curve_period: curve_period_index = curve_period.index(map_period) one_slice_vel_list.append(curve_vel[curve_period_index]) else: one_slice_vel_list.append(style_parameter['nan_value']) # get color for dispersion values one_slice_vel_mean = np.nanmean(one_slice_vel_list) one_slice_vel_std = np.nanstd(one_slice_vel_list) color_min = one_slice_vel_mean - one_slice_vel_std * style_parameter['spread_factor'] color_max = one_slice_vel_mean + one_slice_vel_std * style_parameter['spread_factor'] color_step = (color_max - color_min)*1./ncolor one_slice_color_list = get_color_list(one_slice_vel_list,color_min,color_max,palette_r,\ style_parameter['nan_value'],style_parameter['nan_color']) colorbar_left = np.linspace(color_min,color_max-color_step,ncolor) colorbar_right = np.linspace(color_min+color_step,color_max,ncolor) if one_slice_lat_list: map_data_all_slices_velocity.append(one_slice_vel_list) map_data_all_slices_period.append('Period: {0:6.1f} s'.format(map_period)) map_data_all_slices_color.append(one_slice_color_list) colorbar_data_all_left.append(colorbar_left) colorbar_data_all_right.append(colorbar_right) # get location for all points map_lat_list, map_lon_list = [], [] map_lat_label_list, map_lon_label_list = [], [] for i in range(ncurve): acurve = curve_data_array[i] map_lat_list.append(acurve['latitude']) map_lon_list.append(acurve['longitude']) map_lat_label_list.append('Lat: {0:12.3f}'.format(acurve['latitude'])) map_lon_label_list.append('Lon: {0:12.3f}'.format(acurve['longitude'])) # data for the map view plot map_view_label_lon = style_parameter['map_view_period_label_lon'] map_view_label_lat = style_parameter['map_view_period_label_lat'] map_data_one_slice = map_data_all_slices_color[style_parameter['map_view_default_index']] map_data_one_slice_period = map_data_all_slices_period[style_parameter['map_view_default_index']] map_data_one_slice_bokeh = ColumnDataSource(data=dict(map_lat_list=map_lat_list,\ map_lon_list=map_lon_list,\ map_data_one_slice=map_data_one_slice)) map_data_one_slice_period_bokeh = ColumnDataSource(data=dict(lat=[map_view_label_lat], lon=[map_view_label_lon], map_period=[map_data_one_slice_period])) map_data_all_slices_bokeh = ColumnDataSource(data=dict(map_data_all_slices_color=map_data_all_slices_color,\ map_data_all_slices_period=map_data_all_slices_period)) # data for the colorbar colorbar_data_one_slice = {} colorbar_data_one_slice['colorbar_left'] = colorbar_data_all_left[style_parameter['map_view_default_index']] colorbar_data_one_slice['colorbar_right'] = colorbar_data_all_right[style_parameter['map_view_default_index']] colorbar_data_one_slice_bokeh = ColumnDataSource(data=dict(colorbar_top=colorbar_top,colorbar_bottom=colorbar_bottom, colorbar_left=colorbar_data_one_slice['colorbar_left'],\ colorbar_right=colorbar_data_one_slice['colorbar_right'],\ palette_r=palette_r)) colorbar_data_all_slices_bokeh = ColumnDataSource(data=dict(colorbar_data_all_left=colorbar_data_all_left,\ colorbar_data_all_right=colorbar_data_all_right)) # data for dispersion curves curve_default_index = style_parameter['curve_default_index'] selected_dot_on_map_bokeh = ColumnDataSource(data=dict(lat=[map_lat_list[curve_default_index]],\ lon=[map_lon_list[curve_default_index]],\ color=[map_data_one_slice[curve_default_index]],\ index=[curve_default_index])) selected_curve_data = curve_data_array[curve_default_index] selected_curve_data_bokeh = ColumnDataSource(data=dict(curve_period=selected_curve_data['period'],\ curve_velocity=selected_curve_data['velocity'])) period_all = [] velocity_all = [] for acurve in curve_data_array: period_all.append(acurve['period']) velocity_all.append(acurve['velocity']) curve_data_all_bokeh = ColumnDataSource(data=dict(period_all=period_all, velocity_all=velocity_all)) selected_curve_lat_label_bokeh = ColumnDataSource(data=dict(x=[style_parameter['curve_lat_label_x']], \ y=[style_parameter['curve_lat_label_y']],\ lat_label=[map_lat_label_list[curve_default_index]])) selected_curve_lon_label_bokeh = ColumnDataSource(data=dict(x=[style_parameter['curve_lon_label_x']], \ y=[style_parameter['curve_lon_label_y']],\ lon_label=[map_lon_label_list[curve_default_index]])) all_curve_lat_label_bokeh = ColumnDataSource(data=dict(map_lat_label_list=map_lat_label_list)) all_curve_lon_label_bokeh = ColumnDataSource(data=dict(map_lon_label_list=map_lon_label_list)) # ============================== map_view = Figure(plot_width=style_parameter['map_view_plot_width'], \ plot_height=style_parameter['map_view_plot_height'], \ y_range=[style_parameter['map_view_lat_min'],\ style_parameter['map_view_lat_max']], x_range=[style_parameter['map_view_lon_min'],\ style_parameter['map_view_lon_max']], tools=style_parameter['map_view_tools'],\ title=style_parameter['map_view_title']) # ------------------------------ # add boundaries to map view # country boundaries map_view.multi_line(boundary_data['country']['longitude'],\ boundary_data['country']['latitude'],color='black',\ line_width=2, level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # marine boundaries map_view.multi_line(boundary_data['marine']['longitude'],\ boundary_data['marine']['latitude'],color='black',\ level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # shoreline boundaries map_view.multi_line(boundary_data['shoreline']['longitude'],\ boundary_data['shoreline']['latitude'],color='black',\ line_width=2, level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # state boundaries map_view.multi_line(boundary_data['state']['longitude'],\ boundary_data['state']['latitude'],color='black',\ level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # ------------------------------ # add period label map_view.rect(style_parameter['map_view_period_box_lon'], style_parameter['map_view_period_box_lat'], \ width=style_parameter['map_view_period_box_width'], height=style_parameter['map_view_period_box_height'], \ width_units='screen',height_units='screen', color='#FFFFFF', line_width=1., line_color='black', level='underlay') map_view.text('lon', 'lat', 'map_period', source=map_data_one_slice_period_bokeh,\ text_font_size=style_parameter['annotating_text_font_size'],text_align='left',level='underlay') # ------------------------------ # plot dots map_view.circle('map_lon_list', 'map_lat_list', color='map_data_one_slice', \ source=map_data_one_slice_bokeh, size=style_parameter['marker_size'],\ line_width=0.2, line_color='black', alpha=1.0,\ selection_color='map_data_one_slice', selection_line_color='black',\ selection_fill_alpha=1.0,\ nonselection_fill_alpha=1.0, nonselection_fill_color='map_data_one_slice',\ nonselection_line_color='black', nonselection_line_alpha=1.0) map_view.circle('lon', 'lat', color='color', source=selected_dot_on_map_bokeh, \ line_color='#00ff00', line_width=4.0, alpha=1.0, \ size=style_parameter['selected_marker_size']) # ------------------------------ # change style map_view.title.text_font_size = style_parameter['title_font_size'] map_view.title.align = 'center' map_view.title.text_font_style = 'normal' map_view.xaxis.axis_label = style_parameter['map_view_xlabel'] map_view.xaxis.axis_label_text_font_style = 'normal' map_view.xaxis.axis_label_text_font_size = xlabel_fontsize map_view.xaxis.major_label_text_font_size = xlabel_fontsize map_view.yaxis.axis_label = style_parameter['map_view_ylabel'] map_view.yaxis.axis_label_text_font_style = 'normal' map_view.yaxis.axis_label_text_font_size = xlabel_fontsize map_view.yaxis.major_label_text_font_size = xlabel_fontsize map_view.xgrid.grid_line_color = None map_view.ygrid.grid_line_color = None map_view.toolbar.logo = None map_view.toolbar_location = 'above' map_view.toolbar_sticky = False # ============================== # plot colorbar colorbar_fig = Figure(tools=[], y_range=(0,0.1),plot_width=style_parameter['map_view_plot_width'], \ plot_height=style_parameter['colorbar_plot_height'],title=style_parameter['colorbar_title']) colorbar_fig.toolbar_location=None colorbar_fig.quad(top='colorbar_top',bottom='colorbar_bottom',left='colorbar_left',right='colorbar_right',\ fill_color='palette_r',source=colorbar_data_one_slice_bokeh) colorbar_fig.yaxis[0].ticker=FixedTicker(ticks=[]) colorbar_fig.xgrid.grid_line_color = None colorbar_fig.ygrid.grid_line_color = None colorbar_fig.xaxis.axis_label_text_font_size = xlabel_fontsize colorbar_fig.xaxis.major_label_text_font_size = xlabel_fontsize colorbar_fig.xaxis[0].formatter = PrintfTickFormatter(format="%5.2f") colorbar_fig.title.text_font_size = xlabel_fontsize colorbar_fig.title.align = 'center' colorbar_fig.title.text_font_style = 'normal' # ============================== curve_fig = Figure(plot_width=style_parameter['curve_plot_width'], plot_height=style_parameter['curve_plot_height'], \ y_range=(style_parameter['curve_y_min'],style_parameter['curve_y_max']), \ x_range=(style_parameter['curve_x_min'],style_parameter['curve_x_max']),x_axis_type='log',\ tools=['save','box_zoom','wheel_zoom','reset','crosshair','pan'], title=style_parameter['curve_title']) # ------------------------------ curve_fig.rect([style_parameter['curve_label_box_x']], [style_parameter['curve_label_box_y']], \ width=style_parameter['curve_label_box_width'], height=style_parameter['curve_label_box_height'], \ width_units='screen', height_units='screen', color='#FFFFFF', line_width=1., line_color='black', level='underlay') curve_fig.text('x', 'y', \ 'lat_label', source=selected_curve_lat_label_bokeh) curve_fig.text('x', 'y', \ 'lon_label', source=selected_curve_lon_label_bokeh) # ------------------------------ curve_fig.line('curve_period', 'curve_velocity', source=selected_curve_data_bokeh, color='black') curve_fig.circle('curve_period', 'curve_velocity', source=selected_curve_data_bokeh, size=5, color='black') # ------------------------------ curve_fig.title.text_font_size = style_parameter['title_font_size'] curve_fig.title.align = 'center' curve_fig.title.text_font_style = 'normal' curve_fig.xaxis.axis_label = style_parameter['curve_xlabel'] curve_fig.xaxis.axis_label_text_font_style = 'normal' curve_fig.xaxis.axis_label_text_font_size = xlabel_fontsize curve_fig.xaxis.major_label_text_font_size = xlabel_fontsize curve_fig.yaxis.axis_label = style_parameter['curve_ylabel'] curve_fig.yaxis.axis_label_text_font_style = 'normal' curve_fig.yaxis.axis_label_text_font_size = xlabel_fontsize curve_fig.yaxis.major_label_text_font_size = xlabel_fontsize curve_fig.xgrid.grid_line_dash = [4, 2] curve_fig.ygrid.grid_line_dash = [4, 2] curve_fig.xaxis[0].formatter = PrintfTickFormatter(format="%4.0f") curve_fig.toolbar.logo = None curve_fig.toolbar_location = 'above' curve_fig.toolbar_sticky = False # ============================== map_data_one_slice_bokeh.callback = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\ map_data_one_slice_bokeh=map_data_one_slice_bokeh,\ selected_curve_data_bokeh=selected_curve_data_bokeh,\ curve_data_all_bokeh=curve_data_all_bokeh,\ selected_curve_lat_label_bokeh=selected_curve_lat_label_bokeh,\ selected_curve_lon_label_bokeh=selected_curve_lon_label_bokeh,\ all_curve_lat_label_bokeh=all_curve_lat_label_bokeh,\ all_curve_lon_label_bokeh=all_curve_lon_label_bokeh), code=""" var inds = Math.round(cb_obj.selected['1d'].indices) selected_dot_on_map_bokeh.data['index'] = [inds] var new_slice = map_data_one_slice_bokeh.data selected_dot_on_map_bokeh.data['lat'] = [new_slice['map_lat_list'][inds]] selected_dot_on_map_bokeh.data['lon'] = [new_slice['map_lon_list'][inds]] selected_dot_on_map_bokeh.data['color'] = [new_slice['map_data_one_slice'][inds]] selected_dot_on_map_bokeh.change.emit() selected_curve_data_bokeh.data['curve_period'] = curve_data_all_bokeh.data['period_all'][inds] selected_curve_data_bokeh.data['curve_velocity'] = curve_data_all_bokeh.data['velocity_all'][inds] selected_curve_data_bokeh.change.emit() var all_lat_labels = all_curve_lat_label_bokeh.data['map_lat_label_list'] var all_lon_labels = all_curve_lon_label_bokeh.data['map_lon_label_list'] selected_curve_lat_label_bokeh.data['lat_label'] = [all_lat_labels[inds]] selected_curve_lon_label_bokeh.data['lon_label'] = [all_lon_labels[inds]] selected_curve_lat_label_bokeh.change.emit() selected_curve_lon_label_bokeh.change.emit() """) # ============================== period_slider_callback = CustomJS(args=dict(map_data_all_slices_bokeh=map_data_all_slices_bokeh,\ map_data_one_slice_bokeh=map_data_one_slice_bokeh,\ colorbar_data_all_slices_bokeh=colorbar_data_all_slices_bokeh, \ colorbar_data_one_slice_bokeh=colorbar_data_one_slice_bokeh,\ selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\ map_data_one_slice_period_bokeh=map_data_one_slice_period_bokeh),\ code=""" var p_index = Math.round(cb_obj.value) var map_data_all_slices = map_data_all_slices_bokeh.data var map_data_new_slice = map_data_all_slices['map_data_all_slices_color'][p_index] map_data_one_slice_bokeh.data['map_data_one_slice'] = map_data_new_slice map_data_one_slice_bokeh.change.emit() var color_data_all_slices = colorbar_data_all_slices_bokeh.data colorbar_data_one_slice_bokeh.data['colorbar_left'] = color_data_all_slices['colorbar_data_all_left'][p_index] colorbar_data_one_slice_bokeh.data['colorbar_right'] = color_data_all_slices['colorbar_data_all_right'][p_index] colorbar_data_one_slice_bokeh.change.emit() var selected_index = selected_dot_on_map_bokeh.data['index'] selected_dot_on_map_bokeh.data['color'] = [map_data_new_slice[selected_index]] selected_dot_on_map_bokeh.change.emit() map_data_one_slice_period_bokeh.data['map_period'] = [map_data_all_slices['map_data_all_slices_period'][p_index]] map_data_one_slice_period_bokeh.change.emit() """) period_slider = Slider(start=0, end=nperiod-1, value=style_parameter['map_view_default_index'], \ step=1, title=style_parameter['period_slider_title'], \ width=style_parameter['period_slider_plot_width'],\ height=50, callback=period_slider_callback) # ============================== curve_slider_callback = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\ map_data_one_slice_bokeh=map_data_one_slice_bokeh,\ selected_curve_data_bokeh=selected_curve_data_bokeh,\ curve_data_all_bokeh=curve_data_all_bokeh,\ selected_curve_lat_label_bokeh=selected_curve_lat_label_bokeh,\ selected_curve_lon_label_bokeh=selected_curve_lon_label_bokeh,\ all_curve_lat_label_bokeh=all_curve_lat_label_bokeh,\ all_curve_lon_label_bokeh=all_curve_lon_label_bokeh),\ code=""" var c_index = Math.round(cb_obj.value) var one_slice = map_data_one_slice_bokeh.data selected_dot_on_map_bokeh.data['index'] = [c_index] selected_dot_on_map_bokeh.data['lat'] = [one_slice['map_lat_list'][c_index]] selected_dot_on_map_bokeh.data['lon'] = [one_slice['map_lon_list'][c_index]] selected_dot_on_map_bokeh.data['color'] = [one_slice['map_data_one_slice'][c_index]] selected_dot_on_map_bokeh.change.emit() selected_curve_data_bokeh.data['curve_period'] = curve_data_all_bokeh.data['period_all'][c_index] selected_curve_data_bokeh.data['curve_velocity'] = curve_data_all_bokeh.data['velocity_all'][c_index] selected_curve_data_bokeh.change.emit() var all_lat_labels = all_curve_lat_label_bokeh.data['map_lat_label_list'] var all_lon_labels = all_curve_lon_label_bokeh.data['map_lon_label_list'] selected_curve_lat_label_bokeh.data['lat_label'] = [all_lat_labels[c_index]] selected_curve_lon_label_bokeh.data['lon_label'] = [all_lon_labels[c_index]] selected_curve_lat_label_bokeh.change.emit() selected_curve_lon_label_bokeh.change.emit() """) curve_slider = Slider(start=0, end=ncurve-1, value=style_parameter['curve_default_index'], \ step=1, title=style_parameter['curve_slider_title'], width=style_parameter['curve_plot_width'],\ height=50, callback=curve_slider_callback) # ============================== # annotating text annotating_fig01 = Div(text=style_parameter['annotating_html01'], \ width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height']) annotating_fig02 = Div(text=style_parameter['annotating_html02'],\ width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height']) # ============================== output_file(filename,title=style_parameter['html_title'],mode=style_parameter['library_source']) left_fig = Column(period_slider, map_view, colorbar_fig, annotating_fig01,\ width=style_parameter['left_column_width'] ) right_fig = Column(curve_slider, curve_fig, annotating_fig02, \ width=style_parameter['right_column_width'] ) layout = Row(left_fig, right_fig) save(layout)
def createPlot(height=600, width=1200): """ Create and return a plot for visualizing transcripts. """ TOOLS = "pan, wheel_zoom, save, reset, tap" p = Figure(title="", y_range=[], webgl=True, tools=TOOLS, toolbar_location="above", plot_height=height, plot_width=width) # This causes title to overlap plot substantially: #p.title.text_font_size = TITLE_FONT_SIZE p.xgrid.grid_line_color = None # get rid of the grid in bokeh p.ygrid.grid_line_color = None # the block of exons, there's mouse hover effect on that quad = p.quad(top="top", bottom="bottom", left="left", right="right", source=blockSource, fill_alpha=0, line_dash="dotted", line_alpha=0.4, line_color='black', hover_fill_color="red", hover_alpha=0.3, hover_line_color="white", nonselection_fill_alpha=0, nonselection_line_alpha=0.4, nonselection_line_color='black') # the block of each vertical transcript, each one can be selected p.quad(top="top", bottom="bottom", right="right", left="left", source=tranSource, fill_alpha=0, line_alpha=0, nonselection_fill_alpha=0, nonselection_line_alpha=0) # what exons really is # Cannot use line_width="height" because it is broken. p.multi_line(xs="xs", ys="ys", line_width=opt.height, color="color", line_alpha="line_alpha", source=source) # the start/stop codon p.inverted_triangle(x="x", y="y", color="color", source=codonSource, size='size', alpha=0.5) # mouse hover on the block p.add_tools( HoverTool(tooltips=[("chromosome", "@chromosome"), ("exon", "@exon"), ("start", "@start"), ("end", "@end")], renderers=[quad])) return p
plot.scatter('x', 'y', source=source, color='black') # create the horizontal histogram x1 = np.random.normal(loc=5.0, size=400) * 100 hhist, hedges = np.histogram(np.array(data['x']).astype(float), bins=20) hzeros = np.zeros(len(hedges)-1) hmax = max(hhist)*1.1 LINE_ARGS = dict(color="#3A5785", line_color=None) ph = Figure(toolbar_location=None, plot_width=plot.plot_width, plot_height=200, x_range=plot.x_range, y_range=(-hmax, hmax), title=None, min_border=10, min_border_left=50) ph.xgrid.grid_line_color = None ph.quad(bottom=0, left=hedges[:-1], right=hedges[1:], top=hhist, color="white", line_color="#3A5785") hh1 = ph.quad(bottom=0, left=hedges[:-1], right=hedges[1:], top=hzeros, alpha=0.5, **LINE_ARGS) hh2 = ph.quad(bottom=0, left=hedges[:-1], right=hedges[1:], top=hzeros, alpha=0.1, **LINE_ARGS) axis_map = { "[Fe/H]": "feh_cannon", "[a/Fe]": "alpha_fe_cannon", "Ca": "ca_abund_sme", "Mg": "mg_abund_sme", } # Set up widgets text = TextInput(title="title", value='my abundance plot')
def plot_3DModel_bokeh(filename, map_data_all_slices, map_depth_all_slices, \ color_range_all_slices, profile_data_all, boundary_data, \ style_parameter): ''' Plot shear velocity maps and velocity profiles using bokeh Input: filename is the filename of the resulting html file map_data_all_slices contains the velocity model parameters saved for map view plots map_depth_all_slices is a list of depths color_range_all_slices is a list of color ranges profile_data_all constains the velocity model parameters saved for profile plots boundary_data is a list of boundaries style_parameter contains plotting parameters Output: None ''' xlabel_fontsize = style_parameter['xlabel_fontsize'] # colorbar_data_all_left = [] colorbar_data_all_right = [] map_view_ndepth = style_parameter['map_view_ndepth'] ncolor = len(palette) colorbar_top = [0.1 for i in range(ncolor)] colorbar_bottom = [0 for i in range(ncolor)] map_data_all_slices_depth = [] for idepth in range(map_view_ndepth): color_min = color_range_all_slices[idepth][0] color_max = color_range_all_slices[idepth][1] color_step = (color_max - color_min) * 1. / ncolor colorbar_left = np.linspace(color_min, color_max - color_step, ncolor) colorbar_right = np.linspace(color_min + color_step, color_max, ncolor) colorbar_data_all_left.append(colorbar_left) colorbar_data_all_right.append(colorbar_right) map_depth = map_depth_all_slices[idepth] map_data_all_slices_depth.append( 'Depth: {0:8.1f} km'.format(map_depth)) # palette_r = palette[::-1] # data for the colorbar colorbar_data_one_slice = {} colorbar_data_one_slice['colorbar_left'] = colorbar_data_all_left[ style_parameter['map_view_default_index']] colorbar_data_one_slice['colorbar_right'] = colorbar_data_all_right[ style_parameter['map_view_default_index']] colorbar_data_one_slice_bokeh = ColumnDataSource(data=dict(colorbar_top=colorbar_top,colorbar_bottom=colorbar_bottom,\ colorbar_left=colorbar_data_one_slice['colorbar_left'],\ colorbar_right=colorbar_data_one_slice['colorbar_right'],\ palette_r=palette_r)) colorbar_data_all_slices_bokeh = ColumnDataSource(data=dict(colorbar_data_all_left=colorbar_data_all_left,\ colorbar_data_all_right=colorbar_data_all_right)) # map_view_label_lon = style_parameter['map_view_depth_label_lon'] map_view_label_lat = style_parameter['map_view_depth_label_lat'] map_data_one_slice_depth = map_data_all_slices_depth[ style_parameter['map_view_default_index']] map_data_one_slice_depth_bokeh = ColumnDataSource(data=dict(lat=[map_view_label_lat], lon=[map_view_label_lon], map_depth=[map_data_one_slice_depth], left=[style_parameter['profile_plot_xmin']], \ right=[style_parameter['profile_plot_xmax']])) # map_view_default_index = style_parameter['map_view_default_index'] #map_data_one_slice = map_data_all_slices[map_view_default_index] # map_color_all_slices = [] for i in range(len(map_data_all_slices)): vmin, vmax = color_range_all_slices[i] map_color = val_to_rgb(map_data_all_slices[i], palette_r, vmin, vmax) map_color_2d = map_color.view('uint32').reshape(map_color.shape[:2]) map_color_all_slices.append(map_color_2d) map_color_one_slice = map_color_all_slices[map_view_default_index] # map_data_one_slice_bokeh = ColumnDataSource(data=dict(x=[style_parameter['map_view_image_lon_min']],\ y=[style_parameter['map_view_image_lat_min']],dw=[style_parameter['nlon']*style_parameter['dlon']],\ dh=[style_parameter['nlat']*style_parameter['dlat']],map_data_one_slice=[map_color_one_slice])) map_data_all_slices_bokeh = ColumnDataSource(data=dict(map_data_all_slices=map_color_all_slices,\ map_data_all_slices_depth=map_data_all_slices_depth)) # ------------------------------ nprofile = len(profile_data_all) grid_lat_list = [] grid_lon_list = [] width_list = [] height_list = [] for iprofile in range(nprofile): aprofile = profile_data_all[iprofile] grid_lat_list.append(aprofile['lat']) grid_lon_list.append(aprofile['lon']) width_list.append(style_parameter['map_view_grid_width']) height_list.append(style_parameter['map_view_grid_height']) grid_data_bokeh = ColumnDataSource(data=dict(lon=grid_lon_list,lat=grid_lat_list,\ width=width_list, height=height_list)) profile_default_index = style_parameter['profile_default_index'] selected_dot_on_map_bokeh = ColumnDataSource(data=dict(lat=[grid_lat_list[profile_default_index]], \ lon=[grid_lon_list[profile_default_index]], \ width=[style_parameter['map_view_grid_width']],\ height=[style_parameter['map_view_grid_height']],\ index=[profile_default_index])) # ------------------------------ profile_vs_all = [] profile_depth_all = [] profile_ndepth = style_parameter['profile_ndepth'] profile_lat_label_list = [] profile_lon_label_list = [] for iprofile in range(nprofile): aprofile = profile_data_all[iprofile] vs_raw = aprofile['vs'] top_raw = aprofile['top'] profile_lat_label_list.append('Lat: {0:12.1f}'.format(aprofile['lat'])) profile_lon_label_list.append('Lon: {0:12.1f}'.format(aprofile['lon'])) vs_plot = [] depth_plot = [] for idepth in range(profile_ndepth): vs_plot.append(vs_raw[idepth]) depth_plot.append(top_raw[idepth]) vs_plot.append(vs_raw[idepth]) depth_plot.append(top_raw[idepth + 1]) profile_vs_all.append(vs_plot) profile_depth_all.append(depth_plot) profile_data_all_bokeh = ColumnDataSource(data=dict(profile_vs_all=profile_vs_all, \ profile_depth_all=profile_depth_all)) selected_profile_data_bokeh = ColumnDataSource(data=dict(vs=profile_vs_all[profile_default_index],\ depth=profile_depth_all[profile_default_index])) selected_profile_lat_label_bokeh = ColumnDataSource(data=\ dict(x=[style_parameter['profile_lat_label_x']], y=[style_parameter['profile_lat_label_y']],\ lat_label=[profile_lat_label_list[profile_default_index]])) selected_profile_lon_label_bokeh = ColumnDataSource(data=\ dict(x=[style_parameter['profile_lon_label_x']], y=[style_parameter['profile_lon_label_y']],\ lon_label=[profile_lon_label_list[profile_default_index]])) all_profile_lat_label_bokeh = ColumnDataSource(data=dict( profile_lat_label_list=profile_lat_label_list)) all_profile_lon_label_bokeh = ColumnDataSource(data=dict( profile_lon_label_list=profile_lon_label_list)) # button_ndepth = style_parameter['button_ndepth'] button_data_all_vs = [] button_data_all_vp = [] button_data_all_rho = [] button_data_all_top = [] for iprofile in range(nprofile): aprofile = profile_data_all[iprofile] button_data_all_vs.append(aprofile['vs'][:button_ndepth]) button_data_all_vp.append(aprofile['vp'][:button_ndepth]) button_data_all_rho.append(aprofile['rho'][:button_ndepth]) button_data_all_top.append(aprofile['top'][:button_ndepth]) button_data_all_bokeh = ColumnDataSource(data=dict(button_data_all_vs=button_data_all_vs,\ button_data_all_vp=button_data_all_vp,\ button_data_all_rho=button_data_all_rho,\ button_data_all_top=button_data_all_top)) # ============================== map_view = Figure(plot_width=style_parameter['map_view_plot_width'], plot_height=style_parameter['map_view_plot_height'], \ tools=style_parameter['map_view_tools'], title=style_parameter['map_view_title'], \ y_range=[style_parameter['map_view_figure_lat_min'], style_parameter['map_view_figure_lat_max']],\ x_range=[style_parameter['map_view_figure_lon_min'], style_parameter['map_view_figure_lon_max']]) # map_view.image_rgba('map_data_one_slice',x='x',\ y='y',dw='dw',dh='dh', source=map_data_one_slice_bokeh, level='image') depth_slider_callback = CustomJS(args=dict(map_data_one_slice_bokeh=map_data_one_slice_bokeh,\ map_data_all_slices_bokeh=map_data_all_slices_bokeh,\ colorbar_data_all_slices_bokeh=colorbar_data_all_slices_bokeh,\ colorbar_data_one_slice_bokeh=colorbar_data_one_slice_bokeh,\ map_data_one_slice_depth_bokeh=map_data_one_slice_depth_bokeh), code=""" var d_index = Math.round(cb_obj.value) var map_data_all_slices = map_data_all_slices_bokeh.data map_data_one_slice_bokeh.data['map_data_one_slice'] = [map_data_all_slices['map_data_all_slices'][d_index]] map_data_one_slice_bokeh.change.emit() var color_data_all_slices = colorbar_data_all_slices_bokeh.data colorbar_data_one_slice_bokeh.data['colorbar_left'] = color_data_all_slices['colorbar_data_all_left'][d_index] colorbar_data_one_slice_bokeh.data['colorbar_right'] = color_data_all_slices['colorbar_data_all_right'][d_index] colorbar_data_one_slice_bokeh.change.emit() map_data_one_slice_depth_bokeh.data['map_depth'] = [map_data_all_slices['map_data_all_slices_depth'][d_index]] map_data_one_slice_depth_bokeh.change.emit() """) depth_slider = Slider(start=0, end=style_parameter['map_view_ndepth']-1, \ value=map_view_default_index, step=1, \ width=style_parameter['map_view_plot_width'],\ title=style_parameter['depth_slider_title'], height=50) depth_slider.js_on_change('value', depth_slider_callback) depth_slider_callback.args["depth_index"] = depth_slider # ------------------------------ # add boundaries to map view # country boundaries map_view.multi_line(boundary_data['country']['longitude'],\ boundary_data['country']['latitude'],color='black',\ line_width=2, level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # marine boundaries map_view.multi_line(boundary_data['marine']['longitude'],\ boundary_data['marine']['latitude'],color='black',\ level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # shoreline boundaries map_view.multi_line(boundary_data['shoreline']['longitude'],\ boundary_data['shoreline']['latitude'],color='black',\ line_width=2, level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # state boundaries map_view.multi_line(boundary_data['state']['longitude'],\ boundary_data['state']['latitude'],color='black',\ level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # ------------------------------ # add depth label map_view.rect(style_parameter['map_view_depth_box_lon'], style_parameter['map_view_depth_box_lat'], \ width=style_parameter['map_view_depth_box_width'], height=style_parameter['map_view_depth_box_height'], \ width_units='screen',height_units='screen', color='#FFFFFF', line_width=1., line_color='black', level='underlay') map_view.text('lon', 'lat', 'map_depth', source=map_data_one_slice_depth_bokeh,\ text_font_size=style_parameter['annotating_text_font_size'],text_align='left',level='underlay') # ------------------------------ map_view.rect('lon', 'lat', width='width', \ width_units='screen', height='height', \ height_units='screen', line_color='gray', line_alpha=0.5, \ selection_line_color='gray', selection_line_alpha=0.5, selection_fill_color=None,\ nonselection_line_color='gray',nonselection_line_alpha=0.5, nonselection_fill_color=None,\ source=grid_data_bokeh, color=None, line_width=1, level='glyph') map_view.rect('lon', 'lat',width='width', \ width_units='screen', height='height', \ height_units='screen', line_color='#00ff00', line_alpha=1.0, \ source=selected_dot_on_map_bokeh, fill_color=None, line_width=3.,level='glyph') # ------------------------------ grid_data_js = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh, \ grid_data_bokeh=grid_data_bokeh,\ profile_data_all_bokeh=profile_data_all_bokeh,\ selected_profile_data_bokeh=selected_profile_data_bokeh,\ selected_profile_lat_label_bokeh=selected_profile_lat_label_bokeh,\ selected_profile_lon_label_bokeh=selected_profile_lon_label_bokeh, \ all_profile_lat_label_bokeh=all_profile_lat_label_bokeh, \ all_profile_lon_label_bokeh=all_profile_lon_label_bokeh, \ ), code=""" var inds = cb_obj.indices var grid_data = grid_data_bokeh.data selected_dot_on_map_bokeh.data['lat'] = [grid_data['lat'][inds]] selected_dot_on_map_bokeh.data['lon'] = [grid_data['lon'][inds]] selected_dot_on_map_bokeh.data['index'] = [inds] selected_dot_on_map_bokeh.change.emit() var profile_data_all = profile_data_all_bokeh.data selected_profile_data_bokeh.data['vs'] = profile_data_all['profile_vs_all'][inds] selected_profile_data_bokeh.data['depth'] = profile_data_all['profile_depth_all'][inds] selected_profile_data_bokeh.change.emit() var all_profile_lat_label = all_profile_lat_label_bokeh.data['profile_lat_label_list'] var all_profile_lon_label = all_profile_lon_label_bokeh.data['profile_lon_label_list'] selected_profile_lat_label_bokeh.data['lat_label'] = [all_profile_lat_label[inds]] selected_profile_lon_label_bokeh.data['lon_label'] = [all_profile_lon_label[inds]] selected_profile_lat_label_bokeh.change.emit() selected_profile_lon_label_bokeh.change.emit() """) grid_data_bokeh.selected.js_on_change('indices', grid_data_js) # ------------------------------ # change style map_view.title.text_font_size = style_parameter['title_font_size'] map_view.title.align = 'center' map_view.title.text_font_style = 'normal' map_view.xaxis.axis_label = style_parameter['map_view_xlabel'] map_view.xaxis.axis_label_text_font_style = 'normal' map_view.xaxis.axis_label_text_font_size = xlabel_fontsize map_view.xaxis.major_label_text_font_size = xlabel_fontsize map_view.yaxis.axis_label = style_parameter['map_view_ylabel'] map_view.yaxis.axis_label_text_font_style = 'normal' map_view.yaxis.axis_label_text_font_size = xlabel_fontsize map_view.yaxis.major_label_text_font_size = xlabel_fontsize map_view.xgrid.grid_line_color = None map_view.ygrid.grid_line_color = None map_view.toolbar.logo = None map_view.toolbar_location = 'above' map_view.toolbar_sticky = False # ============================== # plot colorbar colorbar_fig = Figure(tools=[], y_range=(0,0.1),plot_width=style_parameter['map_view_plot_width'], \ plot_height=style_parameter['colorbar_plot_height'],title=style_parameter['colorbar_title']) colorbar_fig.toolbar_location = None colorbar_fig.quad(top='colorbar_top',bottom='colorbar_bottom',left='colorbar_left',right='colorbar_right',\ color='palette_r',source=colorbar_data_one_slice_bokeh) colorbar_fig.yaxis[0].ticker = FixedTicker(ticks=[]) colorbar_fig.xgrid.grid_line_color = None colorbar_fig.ygrid.grid_line_color = None colorbar_fig.xaxis.axis_label_text_font_size = xlabel_fontsize colorbar_fig.xaxis.major_label_text_font_size = xlabel_fontsize colorbar_fig.xaxis[0].formatter = PrintfTickFormatter(format="%5.2f") colorbar_fig.title.text_font_size = xlabel_fontsize colorbar_fig.title.align = 'center' colorbar_fig.title.text_font_style = 'normal' # ============================== profile_xrange = Range1d(start=style_parameter['profile_plot_xmin'], end=style_parameter['profile_plot_xmax']) profile_yrange = Range1d(start=style_parameter['profile_plot_ymax'], end=style_parameter['profile_plot_ymin']) profile_fig = Figure(plot_width=style_parameter['profile_plot_width'], plot_height=style_parameter['profile_plot_height'],\ x_range=profile_xrange, y_range=profile_yrange, tools=style_parameter['profile_tools'],\ title=style_parameter['profile_title']) profile_fig.line('vs', 'depth', source=selected_profile_data_bokeh, line_width=2, line_color='black') # ------------------------------ # add lat, lon profile_fig.rect([style_parameter['profile_label_box_x']], [style_parameter['profile_label_box_y']],\ width=style_parameter['profile_label_box_width'], height=style_parameter['profile_label_box_height'],\ width_units='screen', height_units='screen', color='#FFFFFF', line_width=1., line_color='black',\ level='underlay') profile_fig.text('x', 'y', 'lat_label', source=selected_profile_lat_label_bokeh) profile_fig.text('x', 'y', 'lon_label', source=selected_profile_lon_label_bokeh) # ------------------------------ # change style profile_fig.xaxis.axis_label = style_parameter['profile_xlabel'] profile_fig.xaxis.axis_label_text_font_style = 'normal' profile_fig.xaxis.axis_label_text_font_size = xlabel_fontsize profile_fig.xaxis.major_label_text_font_size = xlabel_fontsize profile_fig.yaxis.axis_label = style_parameter['profile_ylabel'] profile_fig.yaxis.axis_label_text_font_style = 'normal' profile_fig.yaxis.axis_label_text_font_size = xlabel_fontsize profile_fig.yaxis.major_label_text_font_size = xlabel_fontsize profile_fig.xgrid.grid_line_dash = [4, 2] profile_fig.ygrid.grid_line_dash = [4, 2] profile_fig.title.text_font_size = style_parameter['title_font_size'] profile_fig.title.align = 'center' profile_fig.title.text_font_style = 'normal' profile_fig.toolbar_location = 'above' profile_fig.toolbar_sticky = False profile_fig.toolbar.logo = None # ============================== profile_slider_callback = CustomJS(args=dict(selected_dot_on_map_bokeh=selected_dot_on_map_bokeh,\ grid_data_bokeh=grid_data_bokeh, \ profile_data_all_bokeh=profile_data_all_bokeh, \ selected_profile_data_bokeh=selected_profile_data_bokeh,\ selected_profile_lat_label_bokeh=selected_profile_lat_label_bokeh,\ selected_profile_lon_label_bokeh=selected_profile_lon_label_bokeh, \ all_profile_lat_label_bokeh=all_profile_lat_label_bokeh, \ all_profile_lon_label_bokeh=all_profile_lon_label_bokeh), code=""" var p_index = Math.round(cb_obj.value) var grid_data = grid_data_bokeh.data selected_dot_on_map_bokeh.data['lat'] = [grid_data['lat'][p_index]] selected_dot_on_map_bokeh.data['lon'] = [grid_data['lon'][p_index]] selected_dot_on_map_bokeh.data['index'] = [p_index] selected_dot_on_map_bokeh.change.emit() var profile_data_all = profile_data_all_bokeh.data selected_profile_data_bokeh.data['vs'] = profile_data_all['profile_vs_all'][p_index] selected_profile_data_bokeh.data['depth'] = profile_data_all['profile_depth_all'][p_index] selected_profile_data_bokeh.change.emit() var all_profile_lat_label = all_profile_lat_label_bokeh.data['profile_lat_label_list'] var all_profile_lon_label = all_profile_lon_label_bokeh.data['profile_lon_label_list'] selected_profile_lat_label_bokeh.data['lat_label'] = [all_profile_lat_label[p_index]] selected_profile_lon_label_bokeh.data['lon_label'] = [all_profile_lon_label[p_index]] selected_profile_lat_label_bokeh.change.emit() selected_profile_lon_label_bokeh.change.emit() """) profile_slider = Slider(start=0, end=nprofile-1, value=style_parameter['profile_default_index'], \ step=1, title=style_parameter['profile_slider_title'], \ width=style_parameter['profile_plot_width'], height=50) profile_slider_callback.args['profile_index'] = profile_slider profile_slider.js_on_change('value', profile_slider_callback) # ============================== simple_text_button_callback = CustomJS(args=dict(button_data_all_bokeh=button_data_all_bokeh,\ selected_dot_on_map_bokeh=selected_dot_on_map_bokeh), \ code=""" var index = selected_dot_on_map_bokeh.data['index'] var button_data_vs = button_data_all_bokeh.data['button_data_all_vs'][index] var button_data_vp = button_data_all_bokeh.data['button_data_all_vp'][index] var button_data_rho = button_data_all_bokeh.data['button_data_all_rho'][index] var button_data_top = button_data_all_bokeh.data['button_data_all_top'][index] var csvContent = "" var i = 0 var temp = csvContent temp += "# Layer Top (km) Vs(km/s) Vp(km/s) Rho(g/cm^3) \\n" while(button_data_vp[i]) { temp+=button_data_top[i].toPrecision(6) + " " + button_data_vs[i].toPrecision(4) + " " + \ button_data_vp[i].toPrecision(4) + " " + button_data_rho[i].toPrecision(4) + "\\n" i = i + 1 } const blob = new Blob([temp], { type: 'text/csv;charset=utf-8;' }) const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = 'vel_model.txt'; link.target = '_blank' link.style.visibility = 'hidden' link.dispatchEvent(new MouseEvent('click')) """) simple_text_button = Button( label=style_parameter['simple_text_button_label'], button_type='default', width=style_parameter['button_width']) simple_text_button.js_on_click(simple_text_button_callback) # ------------------------------ model96_button_callback = CustomJS(args=dict(button_data_all_bokeh=button_data_all_bokeh,\ selected_dot_on_map_bokeh=selected_dot_on_map_bokeh), \ code=""" var index = selected_dot_on_map_bokeh.data['index'] var lat = selected_dot_on_map_bokeh.data['lat'] var lon = selected_dot_on_map_bokeh.data['lon'] var button_data_vs = button_data_all_bokeh.data['button_data_all_vs'][index] var button_data_vp = button_data_all_bokeh.data['button_data_all_vp'][index] var button_data_rho = button_data_all_bokeh.data['button_data_all_rho'][index] var button_data_top = button_data_all_bokeh.data['button_data_all_top'][index] var csvContent = "" var i = 0 var temp = csvContent temp += "MODEL." + index + " \\n" temp += "ShearVelocityModel Lat: "+ lat +" Lon: " + lon + "\\n" temp += "ISOTROPIC \\n" temp += "KGS \\n" temp += "SPHERICAL EARTH \\n" temp += "1-D \\n" temp += "CONSTANT VELOCITY \\n" temp += "LINE08 \\n" temp += "LINE09 \\n" temp += "LINE10 \\n" temp += "LINE11 \\n" temp += " H(KM) VP(KM/S) VS(KM/S) RHO(GM/CC) QP QS ETAP ETAS FREFP FREFS \\n" while(button_data_vp[i+1]) { var thickness = button_data_top[i+1] - button_data_top[i] temp+=" " +thickness.toPrecision(6) + " " + button_data_vp[i].toPrecision(4) + " " + button_data_vs[i].toPrecision(4) \ + " " + button_data_rho[i].toPrecision(4) + " 0.00 0.00 0.00 0.00 1.00 1.00" + "\\n" i = i + 1 } const blob = new Blob([temp], { type: 'text/csv;charset=utf-8;' }) const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = 'vel_model96.txt'; link.target = '_blank' link.style.visibility = 'hidden' link.dispatchEvent(new MouseEvent('click')) """) model96_button = Button(label=style_parameter['model96_button_label'], button_type='default', width=style_parameter['button_width']) model96_button.js_on_click(model96_button_callback) # ============================== # annotating text annotating_fig01 = Div(text=style_parameter['annotating_html01'], \ width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height']) annotating_fig02 = Div(text=style_parameter['annotating_html02'],\ width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height']) # ============================== output_file(filename, title=style_parameter['html_title'], mode=style_parameter['library_source']) left_column = Column(depth_slider, map_view, colorbar_fig, annotating_fig01, width=style_parameter['left_column_width']) button_pannel = Row(simple_text_button, model96_button) right_column = Column(profile_slider, profile_fig, button_pannel, annotating_fig02, width=style_parameter['right_column_width']) layout = Row(left_column, right_column) save(layout)
def hist_viz( hist: List[Tuple[np.ndarray, np.ndarray]], nrows: List[int], col: str, yscale: str, plot_width: int, plot_height: int, show_yticks: bool, orig: List[str], df_labels: List[str], ) -> Figure: """ Render a histogram """ # pylint: disable=too-many-arguments,too-many-locals tooltips = [ ("Bin", "@intvl"), ("Frequency", "@freq"), ("Percent", "@pct{0.2f}%"), ("Source", "@orig"), ] fig = Figure( plot_height=plot_height, plot_width=plot_width, title=col, toolbar_location=None, y_axis_type=yscale, ) for i, hst in enumerate(hist): counts, bins = hst if sum(counts) == 0: fig.rect(x=0, y=0, width=0, height=0) continue intvls = _format_bin_intervals(bins) df = pd.DataFrame({ "intvl": intvls, "left": bins[:-1], "right": bins[1:], "freq": counts, "pct": counts / nrows[i] * 100, "orig": orig[i], }) bottom = 0 if yscale == "linear" or df.empty else counts.min() / 2 fig.quad( source=df, left="left", right="right", bottom=bottom, alpha=0.5, top="freq", fill_color=CATEGORY10[i], line_color=CATEGORY10[i], ) hover = HoverTool(tooltips=tooltips, attachment="vertical", mode="vline") fig.add_tools(hover) tweak_figure(fig, "hist", show_yticks) fig.yaxis.axis_label = "Frequency" _format_axis(fig, df.iloc[0]["left"], df.iloc[-1]["right"], "x") x_axis_label = "" if show_yticks: x_axis_label += col if yscale == "linear": _format_axis(fig, 0, df["freq"].max(), "y") if orig != df_labels: if x_axis_label: x_axis_label += f", this vairable is only in {','.join(orig)}" else: x_axis_label += f"This vairable is only in {','.join(orig)}" fig.xaxis.axis_label = x_axis_label fig.xaxis.axis_label_standoff = 0 return fig
d5 = {'kind': 'cash', 'value': 15, 'max_cash': 30} projection = Portfolio(Asset(**d1), Asset(**d2), Asset(**d3), Asset(**d4), Asset(**d5), prd=200) source = ColumnDataSource(projection.gen_quads()) TOOLS = "crosshair, pan, reset, resize, wheel_zoom" plot = Figure(tools=TOOLS, x_axis_type='datetime', plot_height=600, plot_width=600, title="FI calculator") p = plot.quad(left='left', right='right', bottom='bottom', top='top', color='color', source=source) def update_graphic(): """Update the data of the Asset dictionaries and recreate the projection. """ projection = Portfolio(Asset(**d1), Asset(**d2), Asset(**d3), Asset(**d4), Asset(**d5), prd=200) bdf_quad = projection.gen_quads() # print(bdf_quad.head()) source.data['bottom'] = bdf_quad['bottom'] source.data['top'] = bdf_quad['top']
ph = Figure(tools='pan,wheel_zoom, reset', toolbar_location='left', plot_width=plot.plot_width, plot_height=200, x_range=plot.x_range, y_range=(-0.1 * hmax, hmax), min_border=10, min_border_left=50, y_axis_location="right") ph.xgrid.grid_line_color = None ph.yaxis.major_label_orientation = 0 qh = ph.quad(bottom=0, left=hedges[:-1], right=hedges[1:], top=hhist, color="#a7bae1", line_color="black") # create the vertical histogram vhist, vedges = np.histogram(source.data['y'], bins='sqrt') vzeros = np.zeros(len(vedges) - 1) vmax = max(vhist) * 1.1 pv = Figure(tools='pan,wheel_zoom, reset', toolbar_location='above', plot_width=200, plot_height=plot.plot_height, x_range=(-0.1 * vmax, vmax), y_range=plot.y_range, min_border=10,
v4 = hst.Potencia[(hst.oscuridad > 80) & (hst.oscuridad < 85)].sum() v5 = hst.Potencia[(hst.oscuridad > 75) & (hst.oscuridad < 80)].sum() v6 = hst.Potencia[(hst.oscuridad > 70) & (hst.oscuridad < 75)].sum() v7 = hst.Potencia[(hst.oscuridad > 65) & (hst.oscuridad < 70)].sum() v8 = hst.Potencia[(hst.oscuridad > 60) & (hst.oscuridad < 65)].sum() v9 = hst.Potencia[(hst.oscuridad > 55) & (hst.oscuridad < 60)].sum() v10 = hst.Potencia[(hst.oscuridad > 50) & (hst.oscuridad < 55)].sum() ac = np.array([v10, v9, v8, v7, v6, v5, v4, v3, v2, v1]) edges = np.arange(50, 101, 5) p3 = Figure(tools=TOOLS) p3.quad(top=ac, bottom=0, left=edges[:-1], right=edges[1:], fill_color="orangered", line_color="white", alpha=1.0) p3.xaxis.axis_label = "Porcentaje oscuridad (%)" p3.yaxis.axis_label = "Potencia (MW)" ######################################################################################## # est_minEner = pd.read_csv('../datos/estaciones_MinEner/infoEstaciones.csv', sep=';', encoding="ISO-8859-1") # est_minEner['Mandante'] = 'Min Energia' # #est_minEner["weblink"] = "http://localhost:6010/est_minEner" # wl = [] # for pl in est_minEner.index: # try: # wl_tmp = "http://localhost:6010/est_minEner" + "?idEst=" + str(int(pl))
''' # Read in the FSAEM data compdata = pd.read_excel('FSAEM_summarized_results.xlsx') source = ColumnDataSource(data=dict()) # Initialize the plot plot = Figure(plot_width=800, plot_height=500, toolbar_location='right', tools="pan,wheel_zoom,box_zoom,reset,resize") freq_bars = plot.quad(top='hist', bottom=0, left='left_edge', right='right_edge', source=source, fill_color='OliveDrab', line_color='#000000') plot.xaxis.axis_label = "Weight [kg]" plot.xaxis.axis_line_color = None plot.xaxis.minor_tick_line_color = None plot.yaxis.axis_label = "Frequency" plot.yaxis.axis_line_color = None plot.yaxis.major_tick_line_color = None plot.yaxis.minor_tick_line_color = None plot.xgrid.grid_line_color = None plot.ygrid.grid_line_color = None
} # Read in the FSAEM data compdata = pd.read_excel('FSAEM_summarized_results.xlsx') source = ColumnDataSource(data=dict()) # Initialize the plot plot = Figure(plot_width=800, plot_height=500, toolbar_location='right', tools="pan,wheel_zoom,box_zoom,reset,resize") freq_bars = plot.quad(top='hist', bottom=0, left='left_edge', right='right_edge', source=source, fill_color=YlOrBr3[0], line_color='#000000') plot.xaxis.axis_label = "Total Score" plot.xaxis.axis_line_color = None plot.xaxis.minor_tick_line_color = None plot.yaxis.axis_label = "Frequency" plot.yaxis.axis_line_color = None plot.yaxis.major_tick_line_color = None plot.yaxis.minor_tick_line_color = None plot.xgrid.grid_line_color = None plot.ygrid.grid_line_color = None
def plot_cross_section_bokeh(filename, map_data_all_slices, map_depth_all_slices, \ color_range_all_slices, cross_data, boundary_data, \ style_parameter): ''' Plot shear velocity maps and cross-sections using bokeh Input: filename is the filename of the resulting html file map_data_all_slices contains the velocity model parameters saved for map view plots map_depth_all_slices is a list of depths color_range_all_slices is a list of color ranges profile_data_all is a list of velocity profiles cross_lat_data_all is a list of cross-sections along latitude lat_value_all is a list of corresponding latitudes for these cross-sections cross_lon_data_all is a list of cross-sections along longitude lon_value_all is a list of corresponding longitudes for these cross-sections boundary_data is a list of boundaries style_parameter contains parameters to customize the plots Output: None ''' xlabel_fontsize = style_parameter['xlabel_fontsize'] # colorbar_data_all_left = [] colorbar_data_all_right = [] map_view_ndepth = style_parameter['map_view_ndepth'] palette_r = palette[::-1] ncolor = len(palette_r) colorbar_top = [0.1 for i in range(ncolor)] colorbar_bottom = [0 for i in range(ncolor)] map_data_all_slices_depth = [] for idepth in range(map_view_ndepth): color_min = color_range_all_slices[idepth][0] color_max = color_range_all_slices[idepth][1] color_step = (color_max - color_min)*1./ncolor colorbar_left = np.linspace(color_min,color_max-color_step,ncolor) colorbar_right = np.linspace(color_min+color_step,color_max,ncolor) colorbar_data_all_left.append(colorbar_left) colorbar_data_all_right.append(colorbar_right) map_depth = map_depth_all_slices[idepth] map_data_all_slices_depth.append('Depth: {0:8.0f} km'.format(map_depth)) # data for the colorbar colorbar_data_one_slice = {} colorbar_data_one_slice['colorbar_left'] = colorbar_data_all_left[style_parameter['map_view_default_index']] colorbar_data_one_slice['colorbar_right'] = colorbar_data_all_right[style_parameter['map_view_default_index']] colorbar_data_one_slice_bokeh = ColumnDataSource(data=dict(colorbar_top=colorbar_top,colorbar_bottom=colorbar_bottom,\ colorbar_left=colorbar_data_one_slice['colorbar_left'],\ colorbar_right=colorbar_data_one_slice['colorbar_right'],\ palette_r=palette_r)) colorbar_data_all_slices_bokeh = ColumnDataSource(data=dict(colorbar_data_all_left=colorbar_data_all_left,\ colorbar_data_all_right=colorbar_data_all_right)) # map_view_label_lon = style_parameter['map_view_depth_label_lon'] map_view_label_lat = style_parameter['map_view_depth_label_lat'] map_data_one_slice_depth = map_data_all_slices_depth[style_parameter['map_view_default_index']] map_data_one_slice_depth_bokeh = ColumnDataSource(data=dict(lat=[map_view_label_lat], lon=[map_view_label_lon], map_depth=[map_data_one_slice_depth])) # map_view_default_index = style_parameter['map_view_default_index'] #map_data_one_slice = map_data_all_slices[map_view_default_index] map_color_all_slices = [] for i in range(len(map_data_all_slices)): vmin, vmax = color_range_all_slices[i] map_color = val_to_rgb(map_data_all_slices[i], palette_r, vmin, vmax) map_color_all_slices.append(map_color) map_color_one_slice = map_color_all_slices[map_view_default_index] # map_data_one_slice_bokeh = ColumnDataSource(data=dict(x=[style_parameter['map_view_image_lon_min']],\ y=[style_parameter['map_view_image_lat_min']],dw=[style_parameter['nlon']],\ dh=[style_parameter['nlat']],map_data_one_slice=[map_color_one_slice])) map_data_all_slices_bokeh = ColumnDataSource(data=dict(map_data_all_slices=map_color_all_slices,\ map_data_all_slices_depth=map_data_all_slices_depth)) # plot_depth = np.shape(cross_data)[0] * style_parameter['cross_ddepth'] plot_lon = great_arc_distance(style_parameter['cross_default_lat0'], style_parameter['cross_default_lon0'],\ style_parameter['cross_default_lat1'], style_parameter['cross_default_lon1']) vs_min = style_parameter['cross_view_vs_min'] vs_max = style_parameter['cross_view_vs_max'] cross_color = val_to_rgb(cross_data, palette_r, vmin, vmax) cross_data_bokeh = ColumnDataSource(data=dict(x=[0],\ y=[plot_depth],dw=[plot_lon],\ dh=[plot_depth],cross_data=[cross_color])) map_line_bokeh = ColumnDataSource(data=dict(lat=[style_parameter['cross_default_lat0'], style_parameter['cross_default_lat1']],\ lon=[style_parameter['cross_default_lon0'], style_parameter['cross_default_lon1']])) # ncolor_cross = len(my_palette) colorbar_top_cross = [0.1 for i in range(ncolor_cross)] colorbar_bottom_cross = [0 for i in range(ncolor_cross)] color_min_cross = style_parameter['cross_view_vs_min'] color_max_cross = style_parameter['cross_view_vs_max'] color_step_cross = (color_max_cross - color_min_cross)*1./ncolor_cross colorbar_left_cross = np.linspace(color_min_cross, color_max_cross-color_step_cross, ncolor_cross) colorbar_right_cross = np.linspace(color_min_cross+color_step_cross, color_max_cross, ncolor_cross) # ============================== map_view = Figure(plot_width=style_parameter['map_view_plot_width'], plot_height=style_parameter['map_view_plot_height'], \ tools=style_parameter['map_view_tools'], title=style_parameter['map_view_title'], \ y_range=[style_parameter['map_view_figure_lat_min'], style_parameter['map_view_figure_lat_max']],\ x_range=[style_parameter['map_view_figure_lon_min'], style_parameter['map_view_figure_lon_max']]) # map_view.image_rgba('map_data_one_slice',x='x',\ y='y',dw='dw',dh='dh',\ source=map_data_one_slice_bokeh, level='image') depth_slider_callback = CustomJS(args=dict(map_data_one_slice_bokeh=map_data_one_slice_bokeh,\ map_data_all_slices_bokeh=map_data_all_slices_bokeh,\ colorbar_data_all_slices_bokeh=colorbar_data_all_slices_bokeh,\ colorbar_data_one_slice_bokeh=colorbar_data_one_slice_bokeh,\ map_data_one_slice_depth_bokeh=map_data_one_slice_depth_bokeh), code=""" var d_index = Math.round(cb_obj.value) var map_data_all_slices = map_data_all_slices_bokeh.data map_data_one_slice_bokeh.data['map_data_one_slice'] = [map_data_all_slices['map_data_all_slices'][d_index]] map_data_one_slice_bokeh.change.emit() var color_data_all_slices = colorbar_data_all_slices_bokeh.data colorbar_data_one_slice_bokeh.data['colorbar_left'] = color_data_all_slices['colorbar_data_all_left'][d_index] colorbar_data_one_slice_bokeh.data['colorbar_right'] = color_data_all_slices['colorbar_data_all_right'][d_index] colorbar_data_one_slice_bokeh.change.emit() map_data_one_slice_depth_bokeh.data['map_depth'] = [map_data_all_slices['map_data_all_slices_depth'][d_index]] map_data_one_slice_depth_bokeh.change.emit() """) depth_slider = Slider(start=0, end=style_parameter['map_view_ndepth']-1, \ value=map_view_default_index, step=1, \ width=style_parameter['map_view_plot_width'],\ title=style_parameter['depth_slider_title'], height=50, \ callback=depth_slider_callback) # ------------------------------ # add boundaries to map view # country boundaries map_view.multi_line(boundary_data['country']['longitude'],\ boundary_data['country']['latitude'],color='black',\ line_width=2, level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # marine boundaries map_view.multi_line(boundary_data['marine']['longitude'],\ boundary_data['marine']['latitude'],color='black',\ level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # shoreline boundaries map_view.multi_line(boundary_data['shoreline']['longitude'],\ boundary_data['shoreline']['latitude'],color='black',\ line_width=2, level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # state boundaries map_view.multi_line(boundary_data['state']['longitude'],\ boundary_data['state']['latitude'],color='black',\ level='underlay',nonselection_line_alpha=1.0,\ nonselection_line_color='black') # ------------------------------ # add depth label map_view.rect(style_parameter['map_view_depth_box_lon'], style_parameter['map_view_depth_box_lat'], \ width=style_parameter['map_view_depth_box_width'], height=style_parameter['map_view_depth_box_height'], \ width_units='screen',height_units='screen', color='#FFFFFF', line_width=1., line_color='black', level='underlay') map_view.text('lon', 'lat', 'map_depth', source=map_data_one_slice_depth_bokeh,\ text_font_size=style_parameter['annotating_text_font_size'],text_align='left',level='underlay') # ------------------------------ map_view.line('lon', 'lat', source=map_line_bokeh, line_dash=[8,2,8,2], line_color='#00ff00',\ nonselection_line_alpha=1.0, line_width=5.,\ nonselection_line_color='black') map_view.text([style_parameter['cross_default_lon0']],[style_parameter['cross_default_lat0']], ['A'], \ text_font_size=style_parameter['title_font_size'],text_align='left') map_view.text([style_parameter['cross_default_lon1']],[style_parameter['cross_default_lat1']], ['B'], \ text_font_size=style_parameter['title_font_size'],text_align='left') # ------------------------------ # change style map_view.title.text_font_size = style_parameter['title_font_size'] map_view.title.align = 'center' map_view.title.text_font_style = 'normal' map_view.xaxis.axis_label = style_parameter['map_view_xlabel'] map_view.xaxis.axis_label_text_font_style = 'normal' map_view.xaxis.axis_label_text_font_size = xlabel_fontsize map_view.xaxis.major_label_text_font_size = xlabel_fontsize map_view.yaxis.axis_label = style_parameter['map_view_ylabel'] map_view.yaxis.axis_label_text_font_style = 'normal' map_view.yaxis.axis_label_text_font_size = xlabel_fontsize map_view.yaxis.major_label_text_font_size = xlabel_fontsize map_view.xgrid.grid_line_color = None map_view.ygrid.grid_line_color = None map_view.toolbar.logo = None map_view.toolbar_location = 'above' map_view.toolbar_sticky = False # ============================== # plot colorbar colorbar_fig = Figure(tools=[], y_range=(0,0.1),plot_width=style_parameter['map_view_plot_width'], \ plot_height=style_parameter['colorbar_plot_height'],title=style_parameter['colorbar_title']) colorbar_fig.toolbar_location=None colorbar_fig.quad(top='colorbar_top',bottom='colorbar_bottom',left='colorbar_left',right='colorbar_right',\ color='palette_r',source=colorbar_data_one_slice_bokeh) colorbar_fig.yaxis[0].ticker=FixedTicker(ticks=[]) colorbar_fig.xgrid.grid_line_color = None colorbar_fig.ygrid.grid_line_color = None colorbar_fig.xaxis.axis_label_text_font_size = xlabel_fontsize colorbar_fig.xaxis.major_label_text_font_size = xlabel_fontsize colorbar_fig.xaxis[0].formatter = PrintfTickFormatter(format="%5.2f") colorbar_fig.title.text_font_size = xlabel_fontsize colorbar_fig.title.align = 'center' colorbar_fig.title.text_font_style = 'normal' # ============================== # annotating text annotating_fig01 = Div(text=style_parameter['annotating_html01'], \ width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height']) annotating_fig02 = Div(text="""<p style="font-size:16px">""", \ width=style_parameter['annotation_plot_width'], height=style_parameter['annotation_plot_height']) # ============================== # plot cross-section along latitude cross_section_plot_width = int(style_parameter['cross_plot_height']*1.0/plot_depth*plot_lon/10.) cross_view = Figure(plot_width=cross_section_plot_width, plot_height=style_parameter['cross_plot_height'], \ tools=style_parameter['cross_view_tools'], title=style_parameter['cross_view_title'], \ y_range=[plot_depth, -30],\ x_range=[0, plot_lon]) cross_view.image_rgba('cross_data',x='x',\ y='y',dw='dw',dh='dh',\ source=cross_data_bokeh, level='image') cross_view.text([plot_lon*0.1], [-10], ['A'], \ text_font_size=style_parameter['title_font_size'],text_align='left',level='underlay') cross_view.text([plot_lon*0.9], [-10], ['B'], \ text_font_size=style_parameter['title_font_size'],text_align='left',level='underlay') # ------------------------------ # change style cross_view.title.text_font_size = style_parameter['title_font_size'] cross_view.title.align = 'center' cross_view.title.text_font_style = 'normal' cross_view.xaxis.axis_label = style_parameter['cross_view_xlabel'] cross_view.xaxis.axis_label_text_font_style = 'normal' cross_view.xaxis.axis_label_text_font_size = xlabel_fontsize cross_view.xaxis.major_label_text_font_size = xlabel_fontsize cross_view.yaxis.axis_label = style_parameter['cross_view_ylabel'] cross_view.yaxis.axis_label_text_font_style = 'normal' cross_view.yaxis.axis_label_text_font_size = xlabel_fontsize cross_view.yaxis.major_label_text_font_size = xlabel_fontsize cross_view.xgrid.grid_line_color = None cross_view.ygrid.grid_line_color = None cross_view.toolbar.logo = None cross_view.toolbar_location = 'right' cross_view.toolbar_sticky = False # ============================== colorbar_fig_right = Figure(tools=[], y_range=(0,0.1),plot_width=cross_section_plot_width, \ plot_height=style_parameter['colorbar_plot_height'],title=style_parameter['colorbar_title']) colorbar_fig_right.toolbar_location=None colorbar_fig_right.quad(top=colorbar_top_cross,bottom=colorbar_bottom_cross,\ left=colorbar_left_cross,right=colorbar_right_cross,\ color=my_palette) colorbar_fig_right.yaxis[0].ticker=FixedTicker(ticks=[]) colorbar_fig_right.xgrid.grid_line_color = None colorbar_fig_right.ygrid.grid_line_color = None colorbar_fig_right.xaxis.axis_label_text_font_size = xlabel_fontsize colorbar_fig_right.xaxis.major_label_text_font_size = xlabel_fontsize colorbar_fig_right.xaxis[0].formatter = PrintfTickFormatter(format="%5.2f") colorbar_fig_right.title.text_font_size = xlabel_fontsize colorbar_fig_right.title.align = 'center' colorbar_fig_right.title.text_font_style = 'normal' # ============================== output_file(filename,title=style_parameter['html_title'], mode=style_parameter['library_source']) left_column = Column(depth_slider, map_view, colorbar_fig, annotating_fig01, width=style_parameter['left_column_width']) right_column = Column(annotating_fig02, cross_view, colorbar_fig_right, width=cross_section_plot_width) layout = Row(left_column, right_column, height=800) save(layout)
pay_debt_faster=True, prd=50, ) test = C1(d=d) source = ColumnDataSource(test.gen_quads()) TOOLS = "crosshair, pan, reset, resize, wheel_zoom" plot = Figure(tools=TOOLS, x_axis_type='datetime', plot_height=600, plot_width=600, title="FI calculator") p = plot.quad(left='left', right='right', bottom='bottom', top='top', color='color', source=source) def update_graphic(): test = C1(d=d) bdf_quad = test.gen_quads() source.data['bottom'] = bdf_quad['bottom'] source.data['top'] = bdf_quad['top'] source.data['left'] = bdf_quad['left'] source.data['right'] = bdf_quad['right'] source.trigger('data', source.data, source.data) # Set up widgets
plot2.border_fill_color = "white" plot2.min_border_left = 0 plot2.circle('x', 'y', source=junk_points, \ fill_color='purple', radius=0.1, line_alpha=0.5, fill_alpha=1.0) plot2.line('x', 'y', source=junk_points, line_color='purple', line_alpha=0.5) rect_points = ColumnDataSource(data=dict(top=[totyield / 2. - 50., 9000, 9000], bottom=[-49.8, 8800, 8800], left=[-49.8, 8800, 9000], strbag=' ', right=[-45, 8800, 9200])) plot1.quad(top="top", bottom="bottom", left="left", right="right", source=rect_points, color="lightgreen", fill_alpha=0.5, line_alpha=0.) plot1.quad(top=49.9, bottom=-49.9, left=-49.8, right=-45, line_color="lightgreen", line_width=3, fill_alpha=0.0) # open box plot1.circle([-47.4], 'top', source=rect_points, radius=1.8, fill_alpha=0.5,
import pandas as pd import numpy as np #Pandas version 0.22.0 #Bokeh version 0.12.10 #Numpy version 1.12.1 from bokeh.io import output_file, show,curdoc from bokeh.models import Quad from bokeh.layouts import row, layout,widgetbox from bokeh.models.widgets import Select,MultiSelect from bokeh.plotting import ColumnDataSource,Figure,reset_output,gridplot d= {'A': [1,1,1,2,2,3,4,4,4,4,4], 'B': [1,2,2,2,3,3,4,5,6,6,6], 'C' : [2,2,2,2,2,3,4,5,6,6,6]} df = pd.DataFrame(data=d) names = ["A","B", "C"] #Since bokeh.charts are deprecated so using the new method using numpy histogram hist,edge = np.histogram(df['A'],bins=4) #This is the method you need to pass the histogram objects to source data here it takes edge values for each bin start and end and hist gives count. source = ColumnDataSource(data={'hist': hist, 'edges_rt': edge[1:], 'edges_lt':edge[:-1]}) plot = Figure(plot_height = 300,plot_width = 400) #The quad is used to display the histogram using bokeh. plot.quad(top='hist', bottom=0, left='edges_lt', right='edges_rt',fill_color="#036564", line_color="#033649",source = source) #When you change the selection it will this function and changes the source data so that values are updated. def callback_menu(attr, old, new): hist,edge = np.histogram(df[menu.value],bins=4) source.data={'hist': hist,'edges_rt': edge[1:], 'edges_lt': edge[:-1]} #These are interacting tools in the final graph menu = MultiSelect(options=names,value= ['A','B'], title='Sensor Data') menu.on_change('value', callback_menu) layout = gridplot([[widgetbox(menu),plot]]) curdoc().add_root(layout)
q1_GDD=[], q3_GDD=[], time=[], timer=[], timel=[], date_str=[])) # Create Input controls current_year = datetime.today().year min_year = Slider(title="Year Start", start=1900, end=current_year, value=1900, step=1) max_year = Slider(title="Year End", start=1900, end=current_year, value=current_year, step=1) station_IDs_str = TextInput(title="Station ID", value='6551') base_temp = Slider(title="Base Temperature (C)", start=0, end=25, value=10, step=1) # Create Figure and Plot hover = HoverTool(tooltips=[ ("Date","@date_str")]) p = Figure(x_axis_type="datetime", plot_width=800, tools=[hover]) p.quad(top='max_GDD', bottom='min_GDD', left='timel', right='timer', source=source, alpha=0.5, color='mediumslateblue', line_color="black", line_alpha=0.5, legend='Min/Max') p.quad(top='q3_GDD', bottom='q1_GDD', left='timel', right='timer', source=source, alpha=0.5, color='black', line_color="black", line_alpha=0.5, legend='25-75 Percentile') p.line(x='time', y='mean_GDD', source = source, color='red', line_width = 2, alpha=0.8, legend='Average' ) p.x_range = DataRange1d(range_padding=0, bounds=None) p.yaxis.axis_label = "GDD" p.xaxis.axis_label = 'Month' # p.xaxis[0].formatter = DatetimeTickFormatter(formats=dict(days=["%B %d"], months=["%B"], years=["%Y"])) # Select Data based on input info def select_data(): # p.title = p.title + str(' (Wait..)') global station_IDs # Make Stations ID's as a list station_IDs=[] [station_IDs.append(int(n)) for n in station_IDs_str.value.split()]
src = ColumnDataSource(data=dict(arr_hist=arr_hist, left=left, right=right)) p = Figure(plot_height=400, plot_width=500, x_range=(xMin, xMax), x_axis_label='parameter', y_axis_label='probability', tools="xpan, xwheel_zoom", active_scroll='xwheel_zoom', active_drag="xpan") p.quad(source=src, bottom=0, top='arr_hist', left='left', right='right', fill_color='cornflowerblue', line_color='black') p.yaxis.major_tick_line_color = None # turn off y-axis major ticks p.yaxis.minor_tick_line_color = None # turn off y-axis minor ticks p.yaxis.major_label_text_font_size = '0pt' # preferred method for removing tick labels #defines the callback to be used: callback_plot = CustomJS(args=dict(src=src, p=p, axis=p.xaxis[0], x_range=p.x_range), code="""
Use bokeh serve historic_histogram_interactive.py to run the plot. ''' # Read in the FSAEM data compdata = pd.read_excel('FSAEM_summarized_results.xlsx') source = ColumnDataSource(data=dict()) # Initialize the plot plot = Figure(plot_width=800, plot_height=500, toolbar_location='right', tools="pan,wheel_zoom,box_zoom,reset,resize") freq_bars = plot.quad(top='hist', bottom=0, left='left_edge', right='right_edge', source=source, fill_color='OliveDrab', line_color='#000000') plot.xaxis.axis_label = "Weight [kg]" plot.xaxis.axis_line_color = None plot.xaxis.minor_tick_line_color = None plot.yaxis.axis_label = "Frequency" plot.yaxis.axis_line_color = None plot.yaxis.major_tick_line_color = None plot.yaxis.minor_tick_line_color = None plot.xgrid.grid_line_color = None plot.ygrid.grid_line_color = None plot.outline_line_color = None
str(int(np.sum(yields['complete2'][:]))), str(int(np.sum(yields['complete3'][:]))), str(int(np.sum(yields['complete4'][:]))), str(int(np.sum(yields['complete5'][:]))), str(int(np.sum(yields['complete6'][:]))), str(int(np.sum(yields['complete7'][:]))), str(int(np.sum(yields['complete8'][:]))), str(int(np.sum(yields['complete9'][:]))), str(int(np.sum(yields['complete10'][:]))), str(int(np.sum(yields['complete11'][:]))), str(int(np.sum(yields['complete12'][:]))), str(int(np.sum(yields['complete13'][:]))), str(int(np.sum(yields['complete14'][:]))) ] hist_plot.quad(top='yields', bottom=0., left='left', right='right', source=total_yield_label, \ color='color', fill_alpha=0.9, line_alpha=1., name='total_yield_label_hover') hist_plot.text('xlabels', 'yields', 'labels', 0., 20, -3, text_align='center', source=total_yield_label, text_color='black') yield_hover = HoverTool(names=["total_yield_label_hover"], mode='mouse', tooltips=""" <div>