def test_Patch(): glyph = Patch() assert glyph.x == "x" assert glyph.y == "y" yield check_fill, glyph yield check_line, glyph yield check_props, glyph, ["x", "y"], FILL, LINE
def test_Patch(): glyph = Patch() assert glyph.x is None assert glyph.y is None check_fill_properties(glyph) check_line_properties(glyph) check_properties_existence(glyph, [ "x", "y", ], FILL, LINE, GLYPH)
def test_Patch(): glyph = Patch() assert glyph.x is None assert glyph.y is None yield check_fill, glyph yield check_line, glyph yield (check_props, glyph, [ "x", "y", ], FILL, LINE)
def test_Patch(): glyph = Patch() assert glyph.x is None assert glyph.y is None yield check_fill_properties, glyph yield check_line_properties, glyph yield (check_properties_existence, glyph, [ "x", "y", ], FILL, LINE, GLYPH)
def test_Patch() -> None: glyph = Patch() assert glyph.x == field("x") assert glyph.y == field("y") check_fill_properties(glyph) check_hatch_properties(glyph) check_line_properties(glyph) check_properties_existence(glyph, [ "x", "y", ], FILL, HATCH, LINE, GLYPH)
h=0.4, url=dict( value="http://bokeh.pydata.org/en/latest/_static/images/logo.png" ), anchor="center")), ("line", Line(x="x", y="y", line_color="#F46D43")), ("multi_line", MultiLine(xs="xs", ys="ys", line_color="#8073AC", line_width=2)), ("oval", Oval(x="x", y="y", width=screen(15), height=screen(25), angle=-0.7, fill_color="#1D91C0")), ("patch", Patch(x="x", y="y", fill_color="#A6CEE3")), ("patches", Patches(xs="xs", ys="ys", fill_color="#FB9A99")), ("quad", Quad(left="x", right="xp01", top="y", bottom="ym01", fill_color="#B3DE69")), ("quadratic", Quadratic(x0="x", y0="y", x1="xp02", y1="y", cx="xp01", cy="yp01", line_color="#4DAF4A", line_width=3)), ("ray", Ray(x="x",
text_source = ColumnDataSource( dict( dates=[d1, d2, d3], times=[dt.time(11, 30)] * 3, texts=["CST (UTC+1)", "CEST (UTC+2)", "CST (UTC+1)"], )) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(x_range=xdr, y_range=ydr, plot_width=800, plot_height=400) plot.title.text = "Daylight Hours - Warsaw, Poland" plot.toolbar_location = None patch1 = Patch(x="dates", y="times", fill_color="skyblue", fill_alpha=0.8) plot.add_glyph(patch1_source, patch1) patch2 = Patch(x="dates", y="times", fill_color="orange", fill_alpha=0.8) plot.add_glyph(patch2_source, patch2) sunrise_line = Line(x="dates", y="sunrises", line_color="yellow", line_width=2, label=value("sunrise")) sunrise_line_renderer = plot.add_glyph(source, sunrise_line) sunset_line = Line(x="dates", y="sunsets", line_color="red",
# # data = models['305']['val_accuracy'] # p1.line([i for i in range(0, len(data) + 1)], [0] + data, legend="CNN2: Kernel Size 8x8", line_width=2, color='orangered') # # p1.xaxis.axis_label_text_font_size = '12pt' # p1.yaxis.axis_label_text_font_size = '12pt' # p1.legend.location = 'bottom_right' data1 = [0] + models['304']['train_accuracy'] data2 = [0] + models['304']['val_accuracy'] x = np.hstack(([i for i in range(0, len(data2))], [i for i in range(0, len(data1))][::-1])) y = np.hstack((data2, data1[::-1])) source = ColumnDataSource(dict(x=x, y=y)) p1.line([i for i in range(0, len(data1) + 1)], data1, legend="Training kernel size 3x3", line_width=2, color='forestgreen', line_dash='dashed') p1.line([i for i in range(0, len(data2) + 1)], data2, legend="Validation kernel size 3x3", line_width=2, color='forestgreen') glyph = Patch(x='x', y='y', fill_color="forestgreen", fill_alpha=0.1, line_alpha=0) p1.add_glyph(source, glyph) data3 = [0] + models['305']['train_accuracy'] data4 = [0] + models['305']['val_accuracy'] x = np.hstack(([i for i in range(0, len(data4))], [i for i in range(0, len(data3))][::-1])) y = np.hstack((data4, data3[::-1])) source = ColumnDataSource(dict(x=x, y=y)) p1.line([i for i in range(0, len(data3) + 1)], data3, legend="Training kernel size 8x8", line_width=2, color='salmon', line_dash='dashed') p1.line([i for i in range(0, len(data4) + 1)], data4, legend="Validation kernel size 8x8", line_width=2, color='salmon') glyph = Patch(x='x', y='y', fill_color="salmon", fill_alpha=0.3, line_alpha=0) p1.add_glyph(source, glyph) p1.xaxis.axis_label_text_font_size = '12pt' p1.yaxis.axis_label_text_font_size = '12pt' p1.legend.location = 'bottom_right'
source = ColumnDataSource(dict(x=x, y=y)) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=300, plot_height=300, h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None) glyph = Patch(x="x", y="y", fill_color="#a6cee3") plot.add_glyph(source, glyph) xaxis = LinearAxis() plot.add_layout(xaxis, 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker)) plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) curdoc().add_root(plot) show(plot)
def plot(self, x, y, marker=None, color=None, scale=['linear', 'linear'], xlabel=None, ylabel=None, fig=None, order=None, data=None, identify=None, id_color='red', label_points=False, exclude=None, **kwargs): """Plot parameter x versus parameter y Parameters ---------- x: str The name of the x axis parameter, e.g. 'SpT' y: str The name of the y axis parameter, e.g. 'Teff' marker: str (optional) The name of the method for the desired marker color: str (optional) The color to use for the points scale: sequence The (x,y) scale for the plot xlabel: str The label for the x-axis ylable : str The label for the y-axis fig: bokeh.plotting.figure (optional) The figure to plot on order: int The polynomial order to fit data: dict Additional data to add to the plot identify: idx, str, sequence Names of sources to highlight in the plot id_color: str The color of the identified points label_points: bool Print the name of the object next to the point Returns ------- bokeh.plotting.figure.Figure The figure object """ # Grab the source and valid params source = copy(self.source) params = [k for k in source.column_names if not k.endswith('_unc')] # Check if the x parameter is a color if '-' in x and all([i in params for i in x.split('-')]): colordata = self.get_data(x)[0] if len(colordata) == 3: _ = source.add(colordata[0], x) _ = source.add(colordata[1], '{}_unc'.format(x)) params.append(x) # Check if the y parameter is a color if '-' in y and all([i in params for i in y.split('-')]): colordata = self.get_data(y)[0] if len(colordata) == 3: _ = source.add(colordata[0], y) _ = source.add(colordata[1], '{}_unc'.format(y)) params.append(y) # Check the params are in the table if x not in params: raise Exception( "'{}' is not a valid x parameter. Please choose from {}". format(x, params)) if y not in params: raise Exception( "'{}' is not a valid y parameter. Please choose from {}". format(y, params)) # Make the figure if fig is None: # Tooltip names can't have '.' or '-' xname = source.add(source.data[x], x.replace('.', '_').replace('-', '_')) yname = source.add(source.data[y], y.replace('.', '_').replace('-', '_')) # Set up hover tool tips = [('Name', '@name'), (x, '@{}'.format(xname)), (y, '@{}'.format(yname))] hover = HoverTool(tooltips=tips, names=['points']) # Make the plot TOOLS = ['pan', 'reset', 'box_zoom', 'save', hover] title = '{} v {}'.format(x, y) fig = figure(plot_width=800, plot_height=500, title=title, y_axis_type=scale[1], x_axis_type=scale[0], tools=TOOLS) # # Exclude sources # if exclude is not None: # exc_idx = [i for i, v in enumerate(source.data['name']) if v in exclude] # patches = {x : [(i, np.nan) for i in exc_idx], # y : [(i, np.nan) for i in exc_idx]} # # source.patch(patches) # Get marker class size = kwargs.get('size', 8) kwargs['size'] = size marker = getattr(fig, marker or self.marker) color = color or self.color marker(x, y, source=source, color=color, fill_alpha=0.7, name='points', **kwargs) # Plot y errorbars yval, yerr = source.data[y], source.data['{}_unc'.format(y)] yval[yval == None] = np.nan yerr[yerr == None] = np.nan y_err_x = [(i, i) for i in source.data[x]] y_err_y = [(i, j) for i, j in zip(yval - yerr, yval + yerr)] fig.multi_line(y_err_x, y_err_y, color=color) # Plot x errorbars xval, xerr = source.data[x], source.data['{}_unc'.format(x)] xval[xval == None] = np.nan xerr[xerr == None] = np.nan x_err_y = [(i, i) for i in source.data[y]] x_err_x = [(i, j) for i, j in zip(xval - xerr, xval + xerr)] fig.multi_line(x_err_x, x_err_y, color=color) # Label points if label_points: labels = LabelSet(x=x, y=y, text='name', level='glyph', x_offset=5, y_offset=5, source=source, render_mode='canvas') fig.add_layout(labels) # Fit polynomial if isinstance(order, int): # Only fit valid values idx = [ n for n, (i, j) in enumerate(zip(xval, yval)) if not hasattr(i, 'mask') and not np.isnan(i) and not hasattr(j, 'mask') and not np.isnan(j) ] xd = np.array(xval, dtype=float)[idx] yd = np.array(yval, dtype=float)[idx] ye = np.array(yerr, dtype=float)[idx] # Plot data label = 'Order {} fit'.format(order) xaxis = np.linspace(min(xd), max(xd), 100) coeffs = None # Fit the polynomial try: coeffs, cov = np.polyfit(x=xd, y=yd, deg=order, w=1. / ye, cov=True) except Exception: try: coeffs, cov = np.polyfit(x=xd, y=yd, deg=order, cov=True) except: pass # Plot the line if coeffs is None or any([np.isnan(i) for i in coeffs]): if self.verbose: print( "Could not fit that data with an order {} polynomial". format(order)) else: # Calculate values and 1-sigma TT = np.vstack([xaxis**(order - i) for i in range(order + 1)]).T yaxis = np.dot(TT, coeffs) C_yi = np.dot(TT, np.dot(cov, TT.T)) sig = np.sqrt(np.diag(C_yi)) # Plot the line and shaded error fig.line(xaxis, yaxis, legend=label, color=color, line_alpha=0.3) xpat = np.hstack((xaxis, xaxis[::-1])) ypat = np.hstack((yaxis + sig, (yaxis - sig)[::-1])) err_source = ColumnDataSource(dict(xaxis=xpat, yaxis=ypat)) glyph = Patch(x='xaxis', y='yaxis', fill_color=color, line_color=None, fill_alpha=0.1) fig.add_glyph(err_source, glyph) # Set axis labels xunit = source.data[x].unit yunit = source.data[y].unit fig.xaxis.axis_label = '{}{}'.format( x, ' [{}]'.format(xunit) if xunit else '') fig.yaxis.axis_label = '{}{}'.format( y, ' [{}]'.format(yunit) if yunit else '') # Formatting fig.legend.location = "top_right" # Identify sources if isinstance(identify, list): id_cat = Catalog('Identified') for obj_id in identify: id_cat.add_SED(self.get_SED(obj_id)) fig = id_cat.plot(x, y, fig=fig, size=size + 5, marker='circle', line_color=id_color, fill_color=None, line_width=2, label_points=True) del id_cat return fig
# Add patches to figure plot = figure( #title="Retaining Wall and Backfill Properties", #title_location="above", x_axis_label='x-axis', y_axis_label='Height (m)', plot_width=350, plot_height=400, y_range=(0, 1.3 * H), x_range=(0, 0.829 * 1.3 * H), toolbar_location=None, background_fill_alpha=0.1) plot.xaxis.visible = False wall = Patch(x='x', y='y', fill_color='#DCDDDE', line_color='black', line_width=1.5) plot.add_glyph(source_wall, wall) earth = Patch(x='x', y='y', fill_color='#FFFF99', line_color='black', line_width=1.5) plot.add_glyph(source_earth, earth) plot.min_border_left = 50 water = Patch(x='x', y='y', fill_color='LightSeaGreen',
def get_map(zipcode, zdf): import matplotlib matplotlib.use('Agg') # load required Python libraries from uszipcode import SearchEngine from bokeh.io import export_png, output_file, show from bokeh.models import ColumnDataSource, GMapOptions, LinearColorMapper, ColorBar, NumeralTickFormatter from bokeh.models.glyphs import Patch from bokeh.plotting import gmap from bokeh.embed import components from bokeh.transform import linear_cmap from bokeh.palettes import inferno import numpy as np import pandas as pd import matplotlib.pyplot as plt from babel.numbers import format_currency #WRITE NOTIFICATION TO LOG print("Beginning Map...") # ns/dsi8 - July 2019 # Project 5 Team: N.Scott, J.Huessy, E.Stokes # Problem 4: Extracting Building Values from Zillow # this function accepts input arguments for zipcode and a dataframe (Zillow Zestimate data) # invoke SearchEngine for zipcode search search = SearchEngine(simple_zipcode=False) # pass a zipcode into search zipcode_data = search.by_zipcode(zipcode) # create a dictionary with retrieved details zip_dict = zipcode_data.to_dict() # get all longitudes, latitudes for specified zip zip_poly = zip_dict['polygon'] # isolate all latitudes for specified zip zip_poly_lat = [poly[1] for poly in zip_poly] # isolate all longitudes for specified zip zip_poly_lng = [poly[0] for poly in zip_poly] # define zipcode border (latitude & longitude) zip_dict_gmap_lat = zip_dict['lat'] zip_dict_gmap_lng = zip_dict['lng'] zip_dict_zipcode = zip_dict['zipcode'] zest_total = zdf['price'].sum() zest_dollar = format_currency(zest_total, 'USD', locale='en_US') # output filename includes zipcode #filename2 = f'''ZIP_{zip_dict_zipcode}_gmap.html''' # mapping options based on Bokeh documentation # https://bokeh.pydata.org/en/latest/docs/reference/models/map_plots.html#bokeh.models.map_plots.GMapOptions map_options = GMapOptions(lat=zip_dict_gmap_lat, lng=zip_dict_gmap_lng, map_type="roadmap", zoom=11) # For GMaps to function, Google requires you obtain and enable an API key: # https://developers.google.com/maps/documentation/javascript/get-api-key # Replace the value below with your personal API key: # p = gmap("GOOGLE_API_KEY", map_options, title="Austin") # map title includes zipcode and TOTAL Zillow "Zestimate" value for specified zipcode p = gmap("", map_options) #, title=f'''ZIPCODE: {zip_dict_zipcode} ----> Zestimate TOTAL: {zest_dollar}''') # based on code from Boston DSI cohort - Jan 2019 source = ColumnDataSource(data=dict(lat=zip_poly_lat, lon=zip_poly_lng)) patch = Patch(x='lon', y='lat', fill_color="blue", fill_alpha=0.08) p.add_glyph(source, patch) #ADDING SCATTERPLOT TO MAP #CREATE COLUMN DATA SOURCE FROM ZIPCODE DATAFRAME x = zdf['long'] y = zdf['lat'] z = zdf['price'] source = ColumnDataSource(dict(x=x, y=y, z=z)) #CREATE COLOR MAPPER FROM PRICE COLUMN mapper = linear_cmap(field_name='z', palette=inferno(256), low=min(z), high=max(z)) #ADD CIRCLES AT EACH LAT/LONG PAIR COLOR-CODED BY PRICE p.circle(x='x', y='y', line_color='black', color=mapper, fill_alpha=1, size=5, source=source) #CURRENCY FORMAT FOR TICKS formatter = NumeralTickFormatter(format='$0,0.00') #ADD COLORBAR LEGEND color_bar = ColorBar(color_mapper=mapper['transform'], width=8, formatter=formatter, location=(0, 0)) p.add_layout(color_bar, 'right') # CREATE HTML/JAVASCRIPT COMPONENTS OF BOKEH PLOT script, div = components(p) return script, div
d2 = summer_start + (summer_end - summer_start) / 2 d3 = summer_end + (calendar_end - summer_end) / 2 text_source = ColumnDataSource( dict( dates=[d1, d2, d3], times=[dt.time(11, 30)] * 3, texts=["CST (UTC+1)", "CEST (UTC+2)", "CST (UTC+1)"], )) plot = Plot(plot_width=800, plot_height=400) plot.title.text = "Daylight Hours 2013 - Warsaw, Poland" plot.toolbar_location = None plot.x_range.range_padding = 0 patch1 = Patch(x="dates", y="times", fill_color="#282e54") plot.add_glyph(patch1_source, patch1) patch2 = Patch(x="dates", y="times", fill_color="#ffdd91") plot.add_glyph(patch2_source, patch2) sunrise_line = Line(x="dates", y="sunrises", line_color="orange", line_width=4) sunrise_line_renderer = plot.add_glyph(source, sunrise_line) sunset_line = Line(x="dates", y="sunsets", line_color="crimson", line_width=4) sunset_line_renderer = plot.add_glyph(source, sunset_line) text = Text(x="dates", y="times", text="texts", text_align="center",
def update_plot(self): today = Timestamp.today().strftime('%Y-%m-%d') today_date = to_datetime(today) df = self.counts_data weights = self.similarities_data.xs(self.school, level='school_name', axis=1) df_all = df[df['school_name'].eq(self.school)] present_academic_year = df['academic_year'].unique()[0] tooltips = ''' <div style="font-size: 12px;"> <span style="font-weight: bold;">@school_name</span> (@school_type, @school_age years old)<br> Grade @grade enrollment, as of @reference_date_string<br> <br> <span style="font-weight: bold;">Attrition</span>: @exit_count_present_cumm (@exit_percent_present_cumm{'0.0%'} change from October 1)<br> <span style="font-weight: bold;">Backfill</span>: @enter_count_present_cumm (@enter_percent_present_cumm{'0.0%'} change from October 1)<br> <span style="font-weight: bold;">Current total enrollment</span>: @total_enrollment </div> ''' ticker_ref = DataFrame({'month': date_range('2014-10-01', '2015-06-01', freq='MS')}) ticker_ref['marker'] = ticker_ref['month'] ticker_ref['month'] = ticker_ref['month'].apply(lambda x: x.strftime('%B')) ticker_ref = ticker_ref.set_index('marker')['month'].to_dict() x_range1d = Range1d(-0.05, 290.0) y_index = max( -df_all['exit_percent_present_cumm'].min(), df_all['enter_percent_present_cumm'].max(), -df_all['exit_percent_past_cumm'].min(), df_all['enter_percent_past_cumm'].max() ) y_range1d = Range1d(-y_index - 0.005, y_index + 0.005) plots = [] focus_cols = ['enter_percent_present_cumm', 'exit_percent_present_cumm'] unique_grades = sorted(df_all['grade'].unique().astype('int')) for grade in unique_grades: grade_weight = weights[grade] benchmark_df = DataFrame(columns=focus_cols) df_copy = df[df['academic_year'].eq(present_academic_year)].copy().set_index(['school_name', 'grade']) for rid, label in sorted(ticker_ref.items(), reverse=True): df_copy = df_copy[df_copy['reference_date'].le(rid)] df_ave = df_copy.groupby(level=['school_name', 'grade'])[focus_cols].tail(1).\ mul(grade_weight, axis=0).sum() / grade_weight.sum() df_ave.name = label benchmark_df = benchmark_df.append(df_ave) benchmark_df = benchmark_df.reset_index() benchmark_df['reference_date'] = benchmark_df['index'].map({y: x for x, y in ticker_ref.items()}) benchmark_df['reference_id'] = benchmark_df['reference_date'].apply(lambda x: x.toordinal()) - \ df_all['reference_date'].min().toordinal() source_df = df_all[df_all['grade'].eq(grade)] source_df_rev = source_df.sort_values('reference_id', ascending=False) source_df_trunc = source_df.loc[source_df['reference_date'].le(today_date), :] source = ColumnDataSource(source_df) source_trunc = ColumnDataSource(source_df_trunc) patch_source = ColumnDataSource(dict( x_past=source_df['reference_id'].tolist() + source_df_rev['reference_id'].tolist(), y_past=source_df['enter_percent_past_cumm'].tolist() + source_df_rev['exit_percent_past_cumm'].tolist() )) plot1 = Plot( x_range=x_range1d, y_range=y_range1d, min_border_bottom=5, min_border_top=10, min_border_right=10, plot_width=700, plot_height=150, title=None, title_text_font_size='0pt', title_text_color='grey', outline_line_alpha=0.0) plot1.add_layout( LinearAxis( axis_label='Grade ' + str(grade), axis_label_text_font_size='9pt', minor_tick_line_alpha=0.0, axis_label_text_color='grey', axis_line_alpha=0.1, major_tick_line_alpha=0.1, major_label_text_color='grey', major_label_text_font_size='7pt', formatter=NumeralTickFormatter(format='0%') ), 'left') patch = Patch(x='x_past', y='y_past', fill_color='#AFAFAD', fill_alpha=0.25, line_alpha=0.0) plot1.add_glyph(patch_source, patch) line1 = Line( x='reference_id', y='enter_percent_present_cumm', line_width=2, line_color='#f7910b', line_alpha=1.0) plot1.add_glyph(source_trunc, line1) line2 = Line( x='reference_id', y='exit_percent_present_cumm', line_width=2, line_color='#f7910b', line_alpha=1.0) plot1.add_glyph(source_trunc, line2) line_h = Line(x='reference_id', y=0, line_width=1, line_color='black', line_alpha=0.1) line_renderer = GlyphRenderer(data_source=source, glyph=line_h, name='line') plot1.add_glyph(source, line_h) for ind, series in benchmark_df.iterrows(): x = series['reference_id'] y_enter = series['enter_percent_present_cumm'] y_exit = series['exit_percent_present_cumm'] label = series['index'] line = Segment(x0=x, x1=x, y0=-y_index, y1=y_index, line_width=1, line_color='#165788', line_alpha=0.1) plot1.add_glyph(line) linec1 = Segment( x0=x - 3, x1=x + 3, y0=y_enter, y1=y_enter, line_width=1, line_color='#ed2939', line_alpha=1.0) plot1.add_glyph(linec1) linec2 = Segment( x0=x - 3, x1=x + 3, y0=y_exit, y1=y_exit, line_width=1, line_color='#ed2939', line_alpha=1.0) plot1.add_glyph(linec2) text = Text(x=x+3, y=-y_index, text=[label], text_font_size='8pt', text_color='grey', text_alpha=0.5) plot1.add_glyph(text) hover_tool = HoverTool( plot=plot1, renderers=[line_renderer], tooltips=tooltips, always_active=False, mode='vline', point_policy='follow_mouse', line_policy='prev') crosshair_tool = CrosshairTool(plot=plot1, dimensions=['height']) zoom_tool = BoxZoomTool(plot=plot1, dimensions=['width']) reset_tool = ResetTool(plot=plot1) save_tool = PreviewSaveTool(plot=plot1) pan_tool = PanTool(plot=plot1, dimensions=['width']) help_tool = HelpTool(plot=plot1, help_tooltip='App help page', redirect='http://data.successacademies.org/blog/') plot1.tools.extend([hover_tool, zoom_tool, pan_tool, reset_tool, save_tool, help_tool, crosshair_tool]) plot1.renderers.extend([line_renderer]) plots.append([plot1]) self.plot.children = plots