def age_hist(dataset, title, color=palette[1]): hist, edges = np.histogram(dataset['Age'].fillna(df['Age'].mean()), bins=18, range=(0, 90)) source = ColumnDataSource({ 'hist': hist, 'edges_left': edges[:-1], 'edges_right': edges[1:] }) hover_tool = HoverTool(tooltips=[('From', '@edges_left'), ('Thru', '@edges_right'), ('Count', '@hist')], mode='vline') p = figure(plot_height=400, title=title, tools=[hover_tool]) p.quad(top='hist', bottom=0, left='edges_left', right='edges_right', source=source, fill_color=color, line_color='black') plot_styler(p) p.xaxis.ticker = SingleIntervalTicker(interval=10, num_minor_ticks=2) p.sizing_mode = 'scale_width' return p
def pi_ticks(fig, interval, axis='x'): ticker = SingleIntervalTicker(interval=interval) if axis == 'x' or axis == 'both': fig.xaxis.ticker = ticker fig.xaxis.formatter = pi_formatter() if axis == 'y' or axis == 'both': fig.yaxis.ticker = ticker fig.yaxis.formatter = pi_formatter()
def doPlot11(data, nrDataSource): p = Line(data, y_mapper_type="log", x=data.columns[0], xlabel=data.columns[0], ylabel=data.columns[1], title="Line graph: " + nrDataSource['name'], responsive=True) p._xaxis.ticker = SingleIntervalTicker(interval=5, num_minor_ticks=10) c = components(p, resources=None, wrap_script=False, wrap_plot_info=True) return c
def create_bokeh_plot(file_path, title, clip_counts, old_bird_clip_counts): output_file(file_path) tools = 'save' # tools = 'hover,save,pan,box_zoom,reset,wheel_zoom' p = figure(plot_width=700, plot_height=700, tools=tools) # Create plot lines. for line_name, (detector_names, line_color) in PLOT_LINE_DATA.items(): create_bokeh_plot_line(p, line_name, detector_names, line_color, clip_counts) # Create Old Bird markers. for marker_name, (detector_name, marker_color) in \ OLD_BIRD_PLOT_DATA.items(): create_bokeh_plot_marker(p, marker_name, detector_name, marker_color, old_bird_clip_counts) p.title.text = title p.title.text_font_size = '12pt' p.axis.major_tick_line_color = None p.axis.minor_tick_line_color = None p.xaxis.axis_label = 'Calls' p.y_range = Range1d(0, 100) ticker = SingleIntervalTicker(interval=20, num_minor_ticks=4) p.yaxis.axis_label = 'Precision (%)' p.yaxis.ticker = ticker grid_line_color = 'black' grid_line_alpha = .3 p.xgrid.grid_line_color = grid_line_color p.xgrid.grid_line_alpha = grid_line_alpha p.ygrid.ticker = ticker p.ygrid.grid_line_color = grid_line_color p.ygrid.grid_line_alpha = grid_line_alpha p.ygrid.minor_grid_line_color = grid_line_color p.ygrid.minor_grid_line_alpha = .1 p.legend.location = 'top_right' p.legend.margin = 0 p.legend.label_text_font_size = '8pt' show(p)
def plot(self): self.fig = self.show_montage_centered( self.signals, self.loc_sec, page_width_sec=self.page_width_secs, chstart=0, chstop=self.current_montage_instance.shape[0], fs=self.fs, ylabels=self.current_montage_instance.montage_labels, yscale=self.yscale, montage=self.current_montage_instance) self.fig.xaxis.axis_label = 'seconds' # make the xgrid mark every second self.fig.xgrid.ticker = SingleIntervalTicker( interval=1.0) # bokeh.models.tickers.SingleIntervalTicker
def get_card_y_responses(study): rows = [str(i) for i in range(study.number_of_rows)] cards = [] cards_y_data = {} for card in study.card_set_y.cards: cards.append(card.name) cards_y_data[card.name] = [0 for x in range(study.number_of_rows)] for response in study.responses: for card_position in response.card_positions: if card_position.card.card_set == study.card_set_y: cards_y_data[card_position.card.name][ card_position.position] += 1 x = [(row, card) for row in rows for card in cards] lists = list(cards_y_data.values()) counts = sum(zip(*lists), ()) title = "Count of each card in card set {} in each row".format( study.card_set_y.name) source = ColumnDataSource(data=dict(x=x, counts=counts)) p = figure( x_range=FactorRange(*x), height=400, sizing_mode="stretch_width", title=title, toolbar_location=None, tools="", ) p.vbar(x="x", top="counts", width=0.9, source=source) p.yaxis.ticker = SingleIntervalTicker(interval=1) p.y_range.start = 0 p.x_range.range_padding = 0.1 p.xaxis.major_label_orientation = 1 p.xgrid.grid_line_color = None script, div = components(p) return script, div
def FFR_chart(data, low, up, name): xdata, ydata, xrng, yrng = set_up(data['Month'], data['Last']) now = dt.now().strftime('%B, %d, %Y') p = figure(width=1400, height=int(700 * 2 / 3), title="CME 30-Day Federal Fund Futures: {}".format(now), x_axis_label='Date', x_axis_type='datetime', y_axis_label='Implied Federal Funds Rate', y_range=yrng, x_range=xrng) p.line(xdata, ydata, color='blue') p.line(xrng, [low, low], color='Black', line_dash='dashed') p.line(xrng, [up, up], color='Black', line_dash='dashed') xpos = len(xdata) // 2 ypos = (low + up) / 2 lbl = Label(x=xdata[xpos], y=ypos - .0005, text='Current FFR Target Range') p.add_layout(lbl) for date in FOMC_MEETINGS: p.line([date, date], yrng, color='black', alpha=0.3) for y in range(0, int(yrng[-1] * 400)): p.line(xrng, y / 400, color='grey', alpha=0.3) ytik = SingleIntervalTicker() ytik.interval = .0025 p.yaxis[0].ticker = ytik p.xaxis[0].ticker.desired_num_ticks = len(xdata) p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None p.yaxis.formatter = NumeralTickFormatter(format="0.00%") export_png(p, filename=name + '.png') return p
y=barclays_y, size=10, line_color="black", fill_color="silver", line_width=0.5) # making scroll active by default poverty.toolbar.active_scroll = poverty.select_one(WheelZoomTool) fsrate.toolbar.active_scroll = fsrate.select_one(WheelZoomTool) unemprate.toolbar.active_scroll = unemprate.select_one(WheelZoomTool) # making a legend pov_color_bar = ColorBar(color_mapper=LinearColorMapper(palette=pov_palette, low=0, high=11), ticker=SingleIntervalTicker(interval=1), title="Population in poverty (%)", label_standoff=12, width=220, orientation="horizontal", border_line_color=None, location=(0, 0)) unemp_color_bar = ColorBar(color_mapper=LinearColorMapper( palette=unemp_palette, low=0, high=7), ticker=SingleIntervalTicker(interval=.5), title="Unemployment rate (%)", label_standoff=12, width=220, orientation="horizontal", border_line_color=None,
def gen_scatter(yvar_str='deficit_gdp', xvar_str='dem_senateseats', start_year='min', main_df=main_df, note_text_list=[], fig_title_str='', fig_path=''): """ Generates one of six different plot types of U.S. deficit/GDP by year, by Democrat held Senate seats or House seats, and by three different measures of political control Args: deficit_component (string): either "deficit", "spending", or "revenues" seat_type (string): either "house" or "senate" df (DataFrame): input data show (boolean): =True shows figure by opening browser page Returns: Y (array_like): aggregate output """ # Create Variables for min and max values and plot buffer amounts if start_year == 'min': min_year = main_df['year'].min() else: min_year = int(start_year) main_df = main_df[main_df['year'] >= min_year] max_year = main_df['year'].max() min_yvar = main_df[yvar_str].min() max_yvar = main_df[yvar_str].max() buffer_pct = 0.075 y_buffer = (max_yvar - min_yvar) * buffer_pct max_seats = main_df[xvar_str].max() min_seats = main_df[xvar_str].min() x_buffer = (max_seats - min_seats) * buffer_pct # Create x and y interval tick marks and gridlines for each plot if xvar_str == 'dem_senateseats': x_tick_interval = 2 x_num_minor_ticks = 2 x_grid_interval = x_tick_interval mid_line = 50 if yvar_str == 'deficit_gdp': y_tick_interval = 5 y_num_minor_ticks = 5 y_grid_interval = y_tick_interval elif yvar_str == 'receipts_gdp': y_tick_interval = 2 y_num_minor_ticks = 2 y_grid_interval = y_tick_interval elif yvar_str == 'spend_nonint_gdp': y_tick_interval = 5 y_num_minor_ticks = 5 y_grid_interval = y_tick_interval elif xvar_str == 'dem_houseseats': x_tick_interval = 10 x_num_minor_ticks = 2 x_grid_interval = x_tick_interval mid_line = 217.5 if yvar_str == 'deficit_gdp': y_tick_interval = 5 y_num_minor_ticks = 5 y_grid_interval = y_tick_interval elif yvar_str == 'receipts_gdp': y_tick_interval = 2 y_num_minor_ticks = 2 y_grid_interval = y_tick_interval elif yvar_str == 'spend_nonint_gdp': y_tick_interval = 5 y_num_minor_ticks = 5 y_grid_interval = y_tick_interval # Create entire time series column data source for main and recession df's main_cds = ColumnDataSource(main_df) # Create entire time series column data source for main and recession df's main_cds = ColumnDataSource(main_df) # Create Full control (WH + Sen + HouseRep) Republican control elements cntrl_all_rep_df = \ main_df[(main_df['president_party'] == 'Republican') & (main_df['dem_senate_maj'] == 0) & (main_df['dem_house_maj'] == 0)] cntrl_all_rep_cds = ColumnDataSource(cntrl_all_rep_df) # Create Full control (WH + Sen + HouseRep) Democrat control elements cntrl_all_dem_df = \ main_df[(main_df['president_party'] == 'Democrat') & (main_df['dem_senate_maj'] == 1) & (main_df['dem_house_maj'] == 1)] cntrl_all_dem_cds = ColumnDataSource(cntrl_all_dem_df) # Create Full control (WH + Sen + HouseRep) split control elements cntrl_all_split_df = \ main_df[((main_df['president_party'] == 'Republican') & ((main_df['dem_senate_maj'] == 1) | (main_df['dem_house_maj'] == 1))) | ((main_df['president_party'] == 'Democrat') & ((main_df['dem_senate_maj'] == 0) | (main_df['dem_house_maj'] == 0)))] cntrl_all_split_cds = ColumnDataSource(cntrl_all_split_df) # Create Senate control (WH + Sen) Republican control elements cntrl_whsen_rep_df = \ main_df[(main_df['president_party'] == 'Republican') & (main_df['dem_senate_maj'] == 0)] cntrl_whsen_rep_cds = ColumnDataSource(cntrl_whsen_rep_df) # Create Senate control (WH + Sen) Democrat control elements cntrl_whsen_dem_df = \ main_df[(main_df['president_party'] == 'Democrat') & (main_df['dem_senate_maj'] == 1)] cntrl_whsen_dem_cds = ColumnDataSource(cntrl_whsen_dem_df) # Create Senate control (WH + Sen) split control elements cntrl_whsen_split_df = \ main_df[((main_df['president_party'] == 'Republican') & (main_df['dem_senate_maj'] == 1)) | ((main_df['president_party'] == 'Democrat') & (main_df['dem_senate_maj'] == 0))] cntrl_whsen_split_cds = ColumnDataSource(cntrl_whsen_split_df) # Create House control (WH + HouseRep) Republican control elements cntrl_whhou_rep_df = \ main_df[(main_df['president_party'] == 'Republican') & (main_df['dem_house_maj'] == 0)] cntrl_whhou_rep_cds = ColumnDataSource(cntrl_whhou_rep_df) # Create House control (WH + HouseRep) Democrat control elements cntrl_whhou_dem_df = \ main_df[(main_df['president_party'] == 'Democrat') & (main_df['dem_house_maj'] == 1)] cntrl_whhou_dem_cds = ColumnDataSource(cntrl_whhou_dem_df) # Create House control (WH + HouseRep) split control elements cntrl_whhou_split_df = \ main_df[((main_df['president_party'] == 'Republican') & (main_df['dem_house_maj'] == 1)) | ((main_df['president_party'] == 'Democrat') & (main_df['dem_house_maj'] == 0))] cntrl_whhou_split_cds = ColumnDataSource(cntrl_whhou_split_df) cntrl_cds_list = \ [[cntrl_all_rep_cds, cntrl_all_dem_cds, cntrl_all_split_cds], [cntrl_whsen_rep_cds, cntrl_whsen_dem_cds, cntrl_whsen_split_cds], [cntrl_whhou_rep_cds, cntrl_whhou_dem_cds, cntrl_whhou_split_cds]] # Output to HTML file fig_title = fig_title_str fig_path = fig_path output_file(fig_path, title=fig_title) # Set legend locations and label variables if yvar_str == 'deficit_gdp': legend_location = 'bottom_right' elif yvar_str == 'spend_nonint_gdp': legend_location = 'top_right' elif yvar_str == 'receipts_gdp': legend_location = 'top_right' if xvar_str == 'dem_senateseats': seat_type = 'Senate' elif xvar_str == 'dem_houseseats': seat_type = 'House' ''' --------------------------------------------------------------------------- Create figure for each of the three party control definitions --------------------------------------------------------------------------- ''' cntrl_str_list = ['all', 'whsen', 'whhou'] panel_title_list = \ ['Full control: (White House + Senate + House of Reps.)', 'Senate control: (White House + Senate)', 'House control: (White House + House of Reps.)'] panel_list = [] for k, v in enumerate(cntrl_str_list): # Create a figure with '% of GDP' as y-axis and num seats as x-axis fig = figure(title=fig_title, plot_height=650, plot_width=1100, x_axis_label='Democrat ' + seat_type + ' seats', x_range=(min_seats - x_buffer, max_seats + x_buffer), y_axis_label='Percent of Gross Domestic Product', y_range=(min_yvar - y_buffer, max_yvar + y_buffer), toolbar_location=None) # Set title font size and axes font sizes fig.title.text_font_size = '15.5pt' fig.xaxis.axis_label_text_font_size = '12pt' fig.xaxis.major_label_text_font_size = '12pt' fig.yaxis.axis_label_text_font_size = '12pt' fig.yaxis.major_label_text_font_size = '12pt' # Modify tick intervals for X-axis and Y-axis fig.yaxis.ticker = \ SingleIntervalTicker(interval=y_tick_interval, num_minor_ticks=y_num_minor_ticks) fig.ygrid.ticker = SingleIntervalTicker(interval=y_grid_interval) fig.xaxis.ticker = \ SingleIntervalTicker(interval=x_tick_interval, num_minor_ticks=x_num_minor_ticks) fig.xgrid.ticker = SingleIntervalTicker(interval=x_grid_interval) # Plotting the scatter point circles fig.circle(x=xvar_str, y=yvar_str, source=cntrl_cds_list[k][0], size=10, line_width=1, line_color='black', fill_color='red', alpha=0.7, muted_alpha=0.2, legend_label='Republican control') fig.circle(x=xvar_str, y=yvar_str, source=cntrl_cds_list[k][1], size=10, line_width=1, line_color='black', fill_color='blue', alpha=0.7, muted_alpha=0.2, legend_label='Democrat control') fig.circle(x=xvar_str, y=yvar_str, source=cntrl_cds_list[k][2], size=10, line_width=1, line_color='black', fill_color='green', alpha=0.7, muted_alpha=0.2, legend_label='Split control') fig.segment(x0=mid_line, y0=-40, x1=mid_line, y1=40, color='black', line_dash='6 2', line_width=2) # Add information on hover if yvar_str == 'deficit_gdp': tool_str = 'Deficit / GDP' elif yvar_str == 'receipts_gdp': tool_str = 'Receipts / GDP' elif yvar_str == 'spend_nonint_gdp': tool_str = 'NonInt Spend / GDP' tooltips = [('Year', '@year'), (tool_str, '@' + yvar_str + '{0.0}' + '%'), ('President', '@president'), ('White House', '@president_party'), ('Rep. House Seats', '@rep_houseseats'), ('Dem. House Seats', '@dem_houseseats'), ('Rep. Senate Seats', '@rep_senateseats'), ('Dem. Senate Seats', '@dem_senateseats')] hover_glyph = fig.circle(x='year', y=yvar_str, source=main_cds, size=10, alpha=0, hover_fill_color='gray', hover_alpha=0.5) fig.add_tools(HoverTool(tooltips=tooltips)) # Turn off scrolling fig.toolbar.active_drag = None # Add legend fig.legend.location = legend_location fig.legend.border_line_width = 2 fig.legend.border_line_color = 'black' fig.legend.border_line_alpha = 1 fig.legend.label_text_font_size = '4mm' # Set legend muting click policy fig.legend.click_policy = 'mute' # Add notes below image for note_text in note_text_list[k]: caption = Title(text=note_text, align='left', text_font_size='4mm', text_font_style='italic') fig.add_layout(caption, 'below') panel = Panel(child=fig, title=panel_title_list[k]) panel_list.append(panel) # Assign the panels to Tabs tabs = Tabs(tabs=panel_list) # Display the generated figure # show(tabs) return tabs
def plot_bokeh(self, filename=None, show=True, savepng=False): curdoc().theme = Theme(BOKEH_THEME_FILE) if filename is not None: if not filename.endswith('.html'): filename += '.html' else: pass bkp.output_file(filename) else: pass # Format the date correction self.data['utcstr'] = self.data['utc'].apply(lambda x: x.isoformat()[0:19]) # Put the dataframe in a useable form self.data['lower'] = self.data.radiance - self.data.sigma self.data['upper'] = self.data.radiance + self.data.sigma self.data['lattandeg'] = self.data.lattan * 180 / np.pi mask = self.data.alttan != self.data.alttan.max() if np.any(mask): m = self.data[self.data.alttan != self.data.alttan.max()].alttan.max() else: m = 1e10 col = np.interp(self.data.alttan, np.linspace(0, m, 256), np.arange(256)).astype(int) self.data['color'] = [Turbo256[c] for c in col] source = bkp.ColumnDataSource(self.data) # Tools tools = [ 'pan', 'box_zoom', 'wheel_zoom', 'xbox_select', 'hover', 'reset', 'save' ] # tool tips tips = [('index', '$index'), ('UTC', '@utcstr'), ('Radiance', '@radiance{0.2f} kR'), ('LTtan', '@loctimetan{2.1f} hr'), ('Lattan', '@lattandeg{3.1f} deg'), ('Alttan', '@alttan{0.f} km')] # Make the figure width, height = 1200, 600 fig0 = bkp.figure(plot_width=width, plot_height=height, x_axis_type='datetime', title=f'{self.species}, {self.query}', x_axis_label='UTC', y_axis_label='Radiance (kR)', y_range=[0, self.data.radiance.max() * 1.5], tools=tools, active_drag="xbox_select") # plot the data dplot = fig0.circle(x='utc', y='radiance', size=7, color='black', legend_label='Data', hover_color='yellow', source=source, selection_color='orange') fig0.line(x='utc', y='radiance', color='black', legend_label='Data', source=source) fig0.xaxis.ticker = DatetimeTicker(num_minor_ticks=5) # Add error bars fig0.add_layout( Whisker(source=source, base='utc', upper='upper', lower='lower')) renderers = [dplot] # Plot the model col = color_generator() modplots, maskedplots = [], [] for modkey, result in self.model_result.items(): c = next(col) # fig0.line(x='utc', y=modkey, source=source, # legend_label=result.label, color=c) maskkey = modkey.replace('model', 'mask') mask = (self.data[maskkey]).to_list() view = CDSView(source=source, filters=[BooleanFilter(mask)]) modplots.append( fig0.circle(x='utc', y=modkey, size=9, color=c, source=source, legend_label=result.label, view=view)) maskkey = modkey.replace('model', 'mask') mask = np.logical_not(self.data[maskkey]).to_list() view = CDSView(source=source, filters=[BooleanFilter(mask)]) maskedplots.append( fig0.circle(x='utc', y=modkey, size=9, source=source, line_color=c, fill_color='yellow', view=view, legend_label=result.label + ' (Data Point Not Used)')) renderers.extend(modplots) renderers.extend(maskedplots) datahover = HoverTool(tooltips=tips, renderers=renderers) fig0.add_tools(datahover) ############## # Plot tangent point color_mapper = LinearColorMapper(palette="Turbo256", low=0, high=m) width, height = 1200, 600 tools = [ 'pan', 'box_zoom', 'wheel_zoom', 'box_select', 'hover', 'reset', 'save' ] fig1 = bkp.figure(plot_width=width, plot_height=height, title=f'Tangent Point Location', x_axis_label='Local Time (hr)', y_axis_label='Latitude (deg)', x_range=[0, 24], y_range=[-90, 90], tools=tools, active_drag="box_select") tanplot = fig1.circle(x='loctimetan', y='lattandeg', size=5, selection_color='orange', hover_color='purple', source=source, color='color') fig1.xaxis.ticker = SingleIntervalTicker(interval=6, num_minor_ticks=6) fig1.yaxis.ticker = SingleIntervalTicker(interval=45, num_minor_ticks=3) color_bar = ColorBar(color_mapper=color_mapper, title='Altitude (km)', label_standoff=12, border_line_color=None, location=(0, 0)) fig1.add_layout(color_bar, 'right') datahover = HoverTool(tooltips=tips, renderers=[tanplot]) fig1.add_tools(datahover) grid = column(fig0, fig1) if filename is not None: bkp.output_file(filename) if savepng: export_png(grid, filename=filename.replace('.html', '.png')) else: pass bkp.save(grid) else: pass if show: bkp.show(grid) return fig0, fig1
def gen_tseries(yvar_str='deficit_gdp', start_year='min', main_df=main_df, recession_df=recession_df, note_text_list=[], fig_title_str='', fig_path=''): """ This function creates a three-panel time-series plot--one panel for each definition of party control--for a particular variable as a percent of GDP. The particular variable is either deficits, receipts, or non-interest spending. Inputs: yvar_str (string): either ''deficit_gdp', 'receipts_gdp', or 'spend_nonint_gdp' """ # Create Variables for min and max values recession_data_length = len(recession_df['Peak']) if start_year == 'min': min_year = main_df['year'].min() else: min_year = int(start_year) main_df = main_df[main_df['year'] >= min_year] max_year = main_df['year'].max() min_yvar = main_df[yvar_str].min() max_yvar = main_df[yvar_str].max() # Create entire time series column data source for main and recession df's main_cds = ColumnDataSource(main_df) # Create Full control (WH + Sen + HouseRep) Republican control elements cntrl_all_rep_df = \ main_df[(main_df['president_party'] == 'Republican') & (main_df['dem_senate_maj'] == 0) & (main_df['dem_house_maj'] == 0)] cntrl_all_rep_cds = ColumnDataSource(cntrl_all_rep_df) # Create Full control (WH + Sen + HouseRep) Democrat control elements cntrl_all_dem_df = \ main_df[(main_df['president_party'] == 'Democrat') & (main_df['dem_senate_maj'] == 1) & (main_df['dem_house_maj'] == 1)] cntrl_all_dem_cds = ColumnDataSource(cntrl_all_dem_df) # Create Full control (WH + Sen + HouseRep) split control elements cntrl_all_split_df = \ main_df[((main_df['president_party'] == 'Republican') & ((main_df['dem_senate_maj'] == 1) | (main_df['dem_house_maj'] == 1))) | ((main_df['president_party'] == 'Democrat') & ((main_df['dem_senate_maj'] == 0) | (main_df['dem_house_maj'] == 0)))] cntrl_all_split_cds = ColumnDataSource(cntrl_all_split_df) # Create Senate control (WH + Sen) Republican control elements cntrl_whsen_rep_df = \ main_df[(main_df['president_party'] == 'Republican') & (main_df['dem_senate_maj'] == 0)] cntrl_whsen_rep_cds = ColumnDataSource(cntrl_whsen_rep_df) # Create Senate control (WH + Sen) Democrat control elements cntrl_whsen_dem_df = \ main_df[(main_df['president_party'] == 'Democrat') & (main_df['dem_senate_maj'] == 1)] cntrl_whsen_dem_cds = ColumnDataSource(cntrl_whsen_dem_df) # Create Senate control (WH + Sen) split control elements cntrl_whsen_split_df = \ main_df[((main_df['president_party'] == 'Republican') & (main_df['dem_senate_maj'] == 1)) | ((main_df['president_party'] == 'Democrat') & (main_df['dem_senate_maj'] == 0))] cntrl_whsen_split_cds = ColumnDataSource(cntrl_whsen_split_df) # Create House control (WH + HouseRep) Republican control elements cntrl_whhou_rep_df = \ main_df[(main_df['president_party'] == 'Republican') & (main_df['dem_house_maj'] == 0)] cntrl_whhou_rep_cds = ColumnDataSource(cntrl_whhou_rep_df) # Create House control (WH + HouseRep) Democrat control elements cntrl_whhou_dem_df = \ main_df[(main_df['president_party'] == 'Democrat') & (main_df['dem_house_maj'] == 1)] cntrl_whhou_dem_cds = ColumnDataSource(cntrl_whhou_dem_df) # Create House control (WH + HouseRep) split control elements cntrl_whhou_split_df = \ main_df[((main_df['president_party'] == 'Republican') & (main_df['dem_house_maj'] == 1)) | ((main_df['president_party'] == 'Democrat') & (main_df['dem_house_maj'] == 0))] cntrl_whhou_split_cds = ColumnDataSource(cntrl_whhou_split_df) cntrl_cds_list = \ [[cntrl_all_rep_cds, cntrl_all_dem_cds, cntrl_all_split_cds], [cntrl_whsen_rep_cds, cntrl_whsen_dem_cds, cntrl_whsen_split_cds], [cntrl_whhou_rep_cds, cntrl_whhou_dem_cds, cntrl_whhou_split_cds]] # Output to HTML file fig_title = fig_title_str fig_path = fig_path output_file(fig_path, title=fig_title) ''' --------------------------------------------------------------------------- Create figure for each of the three party control definitions --------------------------------------------------------------------------- ''' cntrl_str_list = ['all', 'whsen', 'whhou'] panel_title_list = \ ['Full control: (White House + Senate + House of Reps.)', 'Senate control: (White House + Senate)', 'House control: (White House + House of Reps.)'] panel_list = [] for k, v in enumerate(cntrl_str_list): # Create a figure with '% of GDP' as y-axis and year as x-axis fig = figure(title=fig_title, plot_height=650, plot_width=1100, x_axis_label='Year', x_range=(min_year - 1, max_year + 1), y_axis_label='Percent of Gross Domestic Product', y_range=(min_yvar - 3, max_yvar + 3), toolbar_location=None) # Set title font size and axes font sizes fig.title.text_font_size = '15.5pt' fig.xaxis.axis_label_text_font_size = '12pt' fig.xaxis.major_label_text_font_size = '12pt' fig.yaxis.axis_label_text_font_size = '12pt' fig.yaxis.major_label_text_font_size = '12pt' # Modify tick intervals for X-axis and Y-axis fig.xaxis.ticker = SingleIntervalTicker(interval=10, num_minor_ticks=2) fig.xgrid.ticker = SingleIntervalTicker(interval=10) fig.yaxis.ticker = SingleIntervalTicker(interval=5, num_minor_ticks=5) fig.ygrid.ticker = SingleIntervalTicker(interval=5) # Create recession bars for x in range(0, recession_data_length): peak_year = recession_df['Peak'][x].year trough_year = recession_df['Trough'][x].year if (peak_year >= min_year and trough_year >= min_year): fig.patch(x=[peak_year, trough_year, trough_year, peak_year], y=[-100, -100, max_yvar + 10, max_yvar + 10], fill_color='gray', fill_alpha=0.4, line_width=0, legend_label='Recession') if (peak_year == trough_year and peak_year >= min_year and trough_year >= min_year): fig.patch( x=[peak_year, trough_year + 1, trough_year + 1, peak_year], y=[-100, -100, max_yvar + 10, max_yvar + 10], fill_color='gray', fill_alpha=0.4, line_width=0, legend_label='Recession') # Plotting the line and scatter point circles fig.line(x='year', y=yvar_str, source=main_cds, color='#423D3C', line_width=2) fig.circle(x='year', y=yvar_str, source=cntrl_cds_list[k][0], size=10, line_width=1, line_color='black', fill_color='red', alpha=0.7, muted_alpha=0.2, legend_label='Republican control') fig.circle(x='year', y=yvar_str, source=cntrl_cds_list[k][1], size=10, line_width=1, line_color='black', fill_color='blue', alpha=0.7, muted_alpha=0.2, legend_label='Democrat control') fig.circle(x='year', y=yvar_str, source=cntrl_cds_list[k][2], size=10, line_width=1, line_color='black', fill_color='green', alpha=0.7, muted_alpha=0.2, legend_label='Split control') # Add information on hover if yvar_str == 'deficit_gdp': tool_str = 'Deficit / GDP' elif yvar_str == 'receipts_gdp': tool_str = 'Receipts / GDP' elif yvar_str == 'spend_nonint_gdp': tool_str = 'NonInt Spend / GDP' tooltips = [('Year', '@year'), (tool_str, '@' + yvar_str + '{0.0}' + '%'), ('President', '@president'), ('White House', '@president_party'), ('Rep. House Seats', '@rep_houseseats'), ('Dem. House Seats', '@dem_houseseats'), ('Rep. Senate Seats', '@rep_senateseats'), ('Dem. Senate Seats', '@dem_senateseats')] hover_glyph = fig.circle(x='year', y=yvar_str, source=main_cds, size=10, alpha=0, hover_fill_color='gray', hover_alpha=0.5) fig.add_tools(HoverTool(tooltips=tooltips)) # Turn off scrolling fig.toolbar.active_drag = None # Add legend fig.legend.location = 'bottom_center' fig.legend.border_line_width = 2 fig.legend.border_line_color = 'black' fig.legend.border_line_alpha = 1 fig.legend.label_text_font_size = '4mm' # Set legend muting click policy fig.legend.click_policy = 'mute' # Add notes below image for note_text in note_text_list[k]: caption = Title(text=note_text, align='left', text_font_size='4mm', text_font_style='italic') fig.add_layout(caption, 'below') panel = Panel(child=fig, title=panel_title_list[k]) panel_list.append(panel) # Assign the panels to Tabs tabs = Tabs(tabs=panel_list) # Display the generated figure # show(tabs) return tabs
plot_width=1200, x_axis_label='Year', x_range=(min_year - 0.5, max_year + 0.5), y_axis_label='Percent of Gross Domestic Product', y_range=(min_deficit - 2, max_deficit + 5), toolbar_location=None) # Set title font size and axes font sizes fig.title.text_font_size = '18pt' fig.xaxis.axis_label_text_font_size = '12pt' fig.xaxis.major_label_text_font_size = '12pt' fig.yaxis.axis_label_text_font_size = '12pt' fig.yaxis.major_label_text_font_size = '12pt' # Modify tick intervals for X-axis and Y-axis fig.xaxis.ticker = SingleIntervalTicker(interval=5, num_minor_ticks=5) fig.xgrid.ticker = SingleIntervalTicker(interval=5) fig.yaxis.ticker = SingleIntervalTicker(interval=3, num_minor_ticks=3) fig.ygrid.ticker = SingleIntervalTicker(interval=3) # Plotting data fig.segment(x0=-3000, y0=0, x1=3000, y1=0, color='gray', line_width=4) bar_width = 0.5 # Bar graph for Net Interest fig.vbar(x='year', top='Primary Deficit', bottom='Total Deficit', source=deficit_cds, width=bar_width, fill_color='#6C9CB2', legend_label='Net Interest')
def gen_tseries_dy(var_list, legend_label_list, df, color_list, marker_list, start_year='min', end_year='max', note_text_list=[], fig_title_str='', fig_path=''): """ This function creates a plot of multiple time series of forecasts of U.S. publicly held national debt. """ # Create Variables for min and max values if start_year == 'min': min_year = df['year'].min() else: min_year = int(start_year) if end_year == 'max': max_year = df['year'].max() else: max_year = int(end_year) df_main = df[(df['year'] >= min_year) & (df['year'] <= max_year)] # Find the min and max yvar values across the list of yvars and create # separate ColumnDataSource objects for each forecast series (this helps # with the hovertools) min_yvar = 100 max_yvar = 0 cds_list = [] for k, yvar in enumerate(var_list): min_yvar = np.minimum(min_yvar, df_main[yvar].min()) max_yvar = np.maximum(max_yvar, df_main[yvar].max()) frcst_df = df_main[['year', yvar]].dropna() frcst_df.rename(columns={yvar: 'debt_gdp'}, inplace=True) frcst_df = frcst_df[['year', 'debt_gdp']] cds_list.append(ColumnDataSource(frcst_df)) # Output to HTML file fig_title = fig_title_str fig_path = fig_path output_file(fig_path, title=fig_title) fig = figure(title=fig_title, plot_height=600, plot_width=1100, x_axis_label='Year', x_range=(min_year - 1, max_year + 1), y_axis_label='Percent of Gross Domestic Product', y_range=(min_yvar - 5, max_yvar + 5), toolbar_location=None) # Set title font size and axes font sizes fig.title.text_font_size = '15pt' fig.xaxis.axis_label_text_font_size = '12pt' fig.xaxis.major_label_text_font_size = '12pt' fig.yaxis.axis_label_text_font_size = '12pt' fig.yaxis.major_label_text_font_size = '12pt' # Modify tick intervals for X-axis and Y-axis fig.xaxis.ticker = SingleIntervalTicker(interval=5, num_minor_ticks=5) fig.xgrid.ticker = SingleIntervalTicker(interval=5) fig.yaxis.ticker = SingleIntervalTicker(interval=10, num_minor_ticks=2) fig.ygrid.ticker = SingleIntervalTicker(interval=10) # Create lines and markers for time series for k, yvar in enumerate(var_list): fig.line(x='year', y='debt_gdp', source=cds_list[k], color=color_list[k], line_width=3, alpha=0.7) fig.scatter(x='year', y='debt_gdp', source=cds_list[k], size=8, line_width=1, line_color='black', fill_color=color_list[k], marker=marker_list[k], line_alpha=0.7, fill_alpha=0.7, legend_label=legend_label_list[k]) # Add vertical dashed line at 2050 fig.segment(x0=2050, y0=90, x1=2050, y1=215, color='black', line_dash='6 4', line_width=2) # Add information on hover tooltips = [('Year', '@year'), ('Debt/GDP','@debt_gdp{0.0}' + '%')] fig.add_tools(HoverTool(tooltips=tooltips, toggleable=False)) # Add legend fig.legend.location = 'top_center' fig.legend.border_line_width = 1 fig.legend.border_line_color = 'black' fig.legend.border_line_alpha = 1 fig.legend.label_text_font_size = '4mm' # Add notes below image for note_text in note_text_list: caption = Title(text=note_text, align='left', text_font_size='4mm', text_font_style='italic') fig.add_layout(caption, 'below') return fig
def gen_hhdist_2bars(x_cat_var, bar_hgt_vars1, bar_hgt_vars2, df, color_list, legend_label_list, note_text_list=[], fig_title_str='', fig_path=''): """ This function creates a bar chart of the effect of a reform on households in different quantiles of the lifetime income distribution """ # Create a list of lifetime income groups x_cat_list = df[x_cat_var].tolist() x = [(inc_cat, var_label) for inc_cat in x_cat_list for var_label in legend_label_list] data1 = [] for obs, inc_cat in enumerate(x_cat_list): data1.append(df[bar_hgt_vars1[0]].iloc[obs]), data1.append(df[bar_hgt_vars1[1]].iloc[obs]) data1.append(df[bar_hgt_vars1[2]].iloc[obs]) data1.append(df[bar_hgt_vars1[3]].iloc[obs]) # data_dict1 = {x_cat_var: df[x_cat_var].tolist(), # legend_label_list[0]: df[bar_hgt_vars1[0]].tolist(), # legend_label_list[1]: df[bar_hgt_vars1[1]].tolist(), # legend_label_list[2]: df[bar_hgt_vars1[2]].tolist(), # legend_label_list[3]: df[bar_hgt_vars1[3]].tolist()} # data1 = zip(data_dict1[legend_label_list[0]], # data_dict1[legend_label_list[1]], # data_dict1[legend_label_list[2]], # data_dict1[legend_label_list[3]]) print('x =', x) # print('data1 =', data1) # yvar_list0 = df[bar_hgt_vars1[0]].tolist() # Solve for ymin and ymax across variables and set buffer amount bar_hgt_vars_all = [*bar_hgt_vars1, *bar_hgt_vars2] min_yvar = 100 max_yvar = -100 cds_list = [] for yvar in bar_hgt_vars_all: min_yvar = np.minimum(min_yvar, df[yvar].min()) max_yvar = np.maximum(max_yvar, df[yvar].max()) df_var = df[['lfinc_qntl', yvar]] df_var.rename(columns={yvar: 'var_pct_chg'}, inplace=True) cds_list.append(ColumnDataSource(df_var)) y_buffer_pct = 0.1 y_range = max_yvar - min_yvar y_buffer_amt = y_buffer_pct * y_range # Output to HTML file fig_title = fig_title_str fig_path = fig_path output_file(fig_path, title=fig_title) fig = figure(title=fig_title, height=600, x_axis_label='Lifetime income quantiles', x_range=x_cat_list, y_axis_label='Percent change', y_range=(min_yvar - y_buffer_amt, max_yvar + y_buffer_amt), toolbar_location=None) # Set title font size and axes font sizes fig.title.text_font_size = '15pt' fig.xaxis.axis_label_text_font_size = '12pt' fig.xaxis.major_label_text_font_size = '12pt' fig.yaxis.axis_label_text_font_size = '12pt' fig.yaxis.major_label_text_font_size = '12pt' # Modify tick intervals for Y-axis fig.yaxis.ticker = SingleIntervalTicker(interval=0.1, num_minor_ticks=5) fig.ygrid.ticker = SingleIntervalTicker(interval=0.1) fig.vbar(x=x, top=data1, width=0.8, color=color_list[0], legend_label=legend_label_list[0]) # # Add information on hover # tooltips = [('Percent change', '@var_pct_chg{0.0}' + '%')] # fig.add_tools(HoverTool(tooltips=tooltips, toggleable=False)) # # Add legend # fig.legend.location = 'top_center' # fig.legend.border_line_width = 1 # fig.legend.border_line_color = 'black' # fig.legend.border_line_alpha = 1 # fig.legend.label_text_font_size = '4mm' # # Add notes below image # for note_text in note_text_list: # caption = Title(text=note_text, align='left', text_font_size='4mm', # text_font_style='italic') # fig.add_layout(caption, 'below') return fig
def TabParcialesKilometricos(df): """ PREPARACION DE DATOS """ # Calculo de los valores agregados AVG_Altitud, MAX_Altitud, MIN_Altitud, \ AVG_Velocidad, MAX_Velocidad, MIN_Velocidad, \ AVG_Ritmo, MAX_Ritmo, MIN_Ritmo, \ AVG_FrecuenciaCardiaca, MAX_FrecuenciaCardiaca, MIN_FrecuenciaCardiaca, \ AVG_Cadencia, MAX_Cadencia, MIN_Cadencia, \ AVG_Temperatura, MAX_Temperatura, MIN_Temperatura, \ AVG_LongitudZancada, MAX_LongitudZancada, MIN_LongitudZancada, \ AVG_Pendiente, MAX_Pendiente , MIN_Pendiente = CalculosVectoresAgregados(df) # Calculo de desniveles finales DesnivelPositivo = df['DesnivelPositivoAcumulado'].max() DesnivelNegativo = df['DesnivelNegativoAcumulado'].max() DesnivelAcumulado = DesnivelPositivo + DesnivelNegativo DesnivelPorKilometro = (DesnivelAcumulado / df['Distancia'].max()) * 1000 # Factor de achatamiento de la altitud if DesnivelPorKilometro > 40: OffsetSuperiorAltitud = 0.1 OffsetInferiorAltitud = 0.03 else: OffsetSuperiorAltitud = 2.5 OffsetInferiorAltitud = 0.5 dfTramosKm = TablaParcialesKilometricos(df) dfTramosKm['Ritmo_STR'] = dfTramosKm.Ritmo.apply( lambda x: FormateoTiempos(x, 'R')) # Seleccion de un subconjunto de datos para visualizar dfBokehParcialesKM = df[[ 'Bloque', 'Distancia', 'Altitud', 'FrecuenciaCardiaca', 'Cadencia' ]].copy() dfBokehParcialesKM['AltitudEscalada'] = Reescalado( dfBokehParcialesKM['Altitud'], [ MIN_Altitud[0] - (MAX_Altitud[0] - MIN_Altitud[0]) * OffsetInferiorAltitud, MAX_Altitud[0] + (MAX_Altitud[0] - MIN_Altitud[0]) * OffsetSuperiorAltitud ], [0, dfTramosKm.Velocidad.max()]) dfBokehParcialesKM['FrecuenciaCardiacaEscalada'] = Reescalado( dfBokehParcialesKM['FrecuenciaCardiaca'], [MIN_FrecuenciaCardiaca[0], MAX_FrecuenciaCardiaca[0]], [0, dfTramosKm.Velocidad.max()]) dfBokehParcialesKM['CadenciaEscalada'] = Reescalado( dfBokehParcialesKM['Cadencia'], [MIN_Cadencia[0], MAX_Cadencia[0]], [0, dfTramosKm.Velocidad.max()]) # Reducion de la frecuencia de muestreo dfBokehParcialesKM_Agg = dfBokehParcialesKM.groupby('Bloque').resample( '10S').agg({ 'Distancia': np.max, 'Cadencia': np.mean }) dfBokehParcialesKM_Agg['Cadencia'] = dfBokehParcialesKM_Agg[ 'Cadencia'].round() dfBokehParcialesKM_Agg['CadenciaEscalada'] = Reescalado( dfBokehParcialesKM_Agg['Cadencia'], [MIN_Cadencia[0], MAX_Cadencia[0]], [0, dfTramosKm.Velocidad.max()]) # Creacion de los ColumnDataSource de origen de Bokeh OrigenParcialesKM = ColumnDataSource(dfBokehParcialesKM) OrigenParcialesKM_Agg = ColumnDataSource(dfBokehParcialesKM_Agg) OrigenTramosKm = ColumnDataSource(dfTramosKm) # Asignacion de tamaño segun el total de puntos if df['Distancia'].max() < 5: SizeCircle = 10 elif df['Distancia'].max() < 10: SizeCircle = 8 else: SizeCircle = 5 # Definicion de la paleta de colores por cadencia MapaColorCadencia = LinearColorMapper(palette=paleta_cadencia, low=110, high=190) """ TRAMOS KILOMETRICOS | STRAVA """ PLT_TramosKm = figure(plot_width=900, plot_height=500, x_range=(0, df['Distancia'].max()), y_range=(0, dfTramosKm.Velocidad.max() * 1.1), tools='', toolbar_location=None) PLT_TramosKm.add_layout( Span(location=AVG_Velocidad[0], dimension='width', line_color=BlueJeans[2], line_dash='dashed', line_width=0.1, line_alpha=0.3)) PLT_BarrasKM = PLT_TramosKm.rect(x='x', y='y', width='Distancia', height='Velocidad', source=OrigenTramosKm, line_width=1, line_color=BlueJeans[2], fill_color=BlueJeans[1]) PLT_TramosKm.add_tools( HoverTool(tooltips=[('', '@Ritmo_STR')], renderers=[PLT_BarrasKM], mode='mouse')) PropiedadesLineas = dict(line_width=2, line_alpha=0.7, line_cap='round', visible=False) PLT_TramosKM_Altitud = PLT_TramosKm.line('Distancia', 'AltitudEscalada', source=OrigenParcialesKM, color=paleta_verde[6], **PropiedadesLineas) PLT_TramosKM_FC = PLT_TramosKm.line('Distancia', 'FrecuenciaCardiacaEscalada', source=OrigenParcialesKM, color=paleta_rojo[6], **PropiedadesLineas) PLT_TramosKM_Cadencia = PLT_TramosKm.circle( 'Distancia', 'CadenciaEscalada', source=OrigenParcialesKM_Agg, size=SizeCircle, line_color=transform('Cadencia', MapaColorCadencia), color=transform('Cadencia', MapaColorCadencia), fill_alpha=1, visible=False) # Atributos PLT_TramosKm.title.text = 'RITMO MEDIO KILOMETRICO' PLT_TramosKm.sizing_mode = 'fixed' PLT_TramosKm.xaxis.axis_label = 'Distancia' PLT_TramosKm.xaxis.formatter = NumeralTickFormatter(format='0 a') PLT_TramosKm.yaxis.axis_label = 'Ritmo [min/km]' PLT_TramosKm.grid.visible = False PLT_TramosKm.yaxis.major_label_overrides = { 1: '16:40', 1.5: '16:06', 2: '8:20', 2.5: '6:40', 3: '5:33', 3.5: '4:45', 4: '4:10', 4.5: '3:42', 5: '3:20', 5.5: '3:01', 6: '2:46', 6.5: '2:34', 7: '2:22' } PLT_TramosKm.xaxis.ticker = SingleIntervalTicker(interval=1000) PLT_TramosKm.xaxis.major_label_overrides = FormateoEjes( OrigenParcialesKM.data['Distancia'], 1000, 1000, 0, 0) """ DATOS EN FORMA DE TABLA POR PARCIALES KILOMETRICOS """ TablaKm = [ TableColumn(field='TramoKm', title='Km', width=40, default_sort='ascending', sortable=False, formatter=StringFormatter(font_style='normal', text_align='center', text_color='black')), TableColumn(field='Ritmo_STR', title='Ritmo[min/Km]', width=80, default_sort='ascending', sortable=False, formatter=StringFormatter(font_style='normal', text_align='center', text_color='black')), TableColumn(field='FrecuenciaCardiaca', title='FC[ppm]', width=80, default_sort='ascending', sortable=False, formatter=NumberFormatter(format='0,0', language='es', rounding='round', font_style='normal', text_align='center', text_color='black')), TableColumn(field='Cadencia', title='Cadencia[ppm]', width=80, default_sort='ascending', sortable=False, formatter=NumberFormatter(format='0,0', language='es', rounding='round', font_style='normal', text_align='center', text_color='black')), TableColumn(field='DesnivelAcumulado', title='Desnivel', width=80, default_sort='ascending', sortable=False, formatter=NumberFormatter(format='0,0', language='es', rounding='round', font_style='normal', text_align='center', text_color='black')) ] PLT_TablaKm = DataTable(source=OrigenTramosKm, columns=TablaKm, width=360, height=550, fit_columns=False, sortable=False, reorderable=False, selectable=True, editable=False, index_position=None, header_row=True, row_height=25) """ BOTONES """ CodigoJS = """ var indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; l0.visible = indexOf.call(checkbox.active,0)>=0; l1.visible = indexOf.call(checkbox.active,1)>=0; l2.visible = indexOf.call(checkbox.active,2)>=0; """ BotonesTramosKm = CheckboxButtonGroup( labels=["Altitud", "Frecuencia Cardiaca", "Cadencia"], active=[], width=300, height=30) CodigoJSTramosKm = CustomJS(code=CodigoJS, args=dict(l0=PLT_TramosKM_Altitud, l1=PLT_TramosKM_FC, l2=PLT_TramosKM_Cadencia, checkbox=BotonesTramosKm)) BotonesTramosKm.js_on_click(CodigoJSTramosKm) """ LAYOUT """ GridGraficaTramosKm = layout([ Column(PLT_TramosKm, width=900, height=500), [ Spacer(width=300, height=30), Column(BotonesTramosKm, width=300, height=30), Spacer(width=300, height=30) ] ], sizing_mode='stretch_width', width=900, height=570) GridTablaTramosKm = layout([ Spacer(width=360, height=25), Column(PLT_TablaKm, width=360, height=550) ], sizing_mode='stretch_width', width=360, height=570) GridAnalisisKm = gridplot([GridGraficaTramosKm, GridTablaTramosKm], ncols=2, sizing_mode='stretch_width', toolbar_location=None, plot_width=1000, plot_height=570) return GridAnalisisKm
def DesnivelPositivoAcumulado(DatosBokeh, EjeX, MetricasAuxiliares): """ GRAFICO AREA | DESNIVEL POSITIVO ACUMULADO """ # Creacion del diccionario de metricas auxiliares DiccionarioVariables = ParametrosVariables(DatosBokeh) # Generacion del codigo JavaScript que habilita la visualizacion de metricas auxiliares CodigoJS = GeneracionCodigoJS(MetricasAuxiliares) # Asignacion de tamaño del punto en graficas discretas SizeCircle = FunctionSizeCircle(DatosBokeh) # Creacion de un grafica PLT = figure(width=1000, height=400, x_range=(DatosBokeh.data[EjeX].min(), DatosBokeh.data[EjeX].max()), y_range=(LimiteEjeY(DatosBokeh, 'DESNIVEL POSITIVO', 'Inferior'), LimiteEjeY(DatosBokeh, 'DESNIVEL POSITIVO', 'Superior')), tools='', toolbar_location=None) # Creacion del area bajo la linea de la metrica a partir del CDS Area = DatosBokeh.to_df().copy().reset_index()[[ EjeX, 'DesnivelPositivo[m]' ]].set_index(EjeX) Area.rename(columns={'DesnivelPositivo[m]': 'Area'}, inplace=True) AreaBottom = Area[::-1] AreaBottom['Area'] = 0 PLT.patch(x=hstack((AreaBottom.index, Area.index)), y=hstack((AreaBottom['Area'], Area['Area'])), color=Lavender[0], alpha=1, line_color=None) # Inclusion de datos PLT_Linea = PLT.line(EjeX, 'DesnivelPositivo[m]', source=DatosBokeh, color=Lavender[1], line_width=2, line_cap='round') PLT.add_tools( HoverTool(tooltips=[('', '@{DesnivelPositivo[m]}{int} m')], renderers=[PLT_Linea], mode='vline')) # Inclusion de lineas auxiliares ListadoMetricasAuxiliares = {} for Metrica in MetricasAuxiliares: if DiccionarioVariables[Metrica]['Tipo'] == 'circle': ListadoMetricasAuxiliares[ 'l' + str(MetricasAuxiliares.index(Metrica))] = PLT.circle( EjeX, DiccionarioVariables[Metrica]['Variable'].split('[', 1)[0] + DiccionarioVariables['DESNIVEL POSITIVO']['Sufijo'], source=DiccionarioVariables[Metrica]['CDS'], size=SizeCircle, line_color=DiccionarioVariables[Metrica]['Color'], color=DiccionarioVariables[Metrica]['Color'], **DiccionarioVariables[Metrica]['Propiedades']) elif DiccionarioVariables[Metrica]['Tipo'] == 'step': ListadoMetricasAuxiliares[ 'l' + str(MetricasAuxiliares.index(Metrica))] = PLT.step( EjeX, DiccionarioVariables[Metrica]['Variable'].split('[', 1)[0] + DiccionarioVariables['DESNIVEL POSITIVO']['Sufijo'], source=DiccionarioVariables[Metrica]['CDS'], color=DiccionarioVariables[Metrica]['Color'], **DiccionarioVariables[Metrica]['Propiedades']) else: ListadoMetricasAuxiliares[ 'l' + str(MetricasAuxiliares.index(Metrica))] = PLT.line( EjeX, DiccionarioVariables[Metrica]['Variable'].split('[', 1)[0] + DiccionarioVariables['DESNIVEL POSITIVO']['Sufijo'], source=DiccionarioVariables[Metrica]['CDS'], color=DiccionarioVariables[Metrica]['Color'], **DiccionarioVariables[Metrica]['Propiedades']) # Atributos PLT.title.text = 'DESNIVEL POSITIVO ACUMULADO' PLT.sizing_mode = 'fixed' PLT.yaxis.axis_label = 'Desnivel positivo acumulado [m]' PLT.yaxis.formatter = NumeralTickFormatter(format='0') PLT.grid.visible = False PLT.yaxis.minor_tick_line_color = None PLT.yaxis.major_label_overrides = FormateoEjes( DatosBokeh.data['DesnivelPositivo[m]'], 100, 1) # Asignacion de opciones de visualizacion del eje X if EjeX == 'Distancia[m]': PLT.xaxis.axis_label = 'Distancia' PLT.xaxis.formatter = NumeralTickFormatter(format='0') if DatosBokeh.data['Distancia[m]'].max() >= 4000: PLT.xaxis.ticker = SingleIntervalTicker(interval=1000) PLT.xaxis.major_label_overrides = FormateoEjes( DatosBokeh.data['Distancia[m]'], 1000, 1000, 0, 0) elif EjeX == 'TiempoActividad': PLT.xaxis.axis_label = 'Tiempo actividad' PLT.xaxis.formatter = DatetimeTickFormatter(hourmin='%H:%M:%S', minutes='%M:%S', seconds='%Ss') PLT.xaxis.ticker = DatetimeTicker() elif EjeX == 'TiempoTotal': PLT.xaxis.axis_label = 'Tiempo total' PLT.xaxis.formatter = DatetimeTickFormatter(hourmin='%H:%M:%S', minutes='%M:%S', seconds='%Ss') PLT.xaxis.ticker = DatetimeTicker() #Botones Botones = CheckboxGroup(labels=MetricasAuxiliares, active=[], width=100, height=380) ListadoMetricasAuxiliares['checkbox'] = Botones CodigoJSFrecuenciaCardiaca = CustomJS(code=CodigoJS, args=ListadoMetricasAuxiliares) Botones.js_on_click(CodigoJSFrecuenciaCardiaca) #Layout GridBotones = layout( [Spacer(width=100, height=25), Column(Botones, width=100, height=375)], sizing_mode='fixed', width=100, height=400) GridGrafica = gridplot([PLT, GridBotones], ncols=2, sizing_mode='stretch_width', toolbar_location=None, plot_width=1100, plot_height=400) return GridGrafica
def gen_tseries_frcst(frcst_var_list, legend_label_list, df=main_df, main_start_year='min', main_end_year='max', full_start_year='min', full_end_year='max', note_text_list=[], fig_title_str='', fig_path=''): """ This function creates a plot of multiple time series of CBO forecasts of U.S. publicly held national debt. """ # Create Variables for min and max values if main_start_year == 'min': main_min_year = df['year'].min() else: main_min_year = int(main_start_year) if full_start_year == 'min': full_min_year = df['year'].min() else: full_min_year = int(full_start_year) if main_end_year == 'max': main_max_year = df['year'].max() else: main_max_year = int(main_end_year) if full_end_year == 'max': full_max_year = df['year'].max() else: full_max_year = int(full_end_year) df_full = df[(df['year'] >= full_min_year) & (df['year'] <= full_max_year)] df_main = df[(df['year'] >= main_min_year) & (df['year'] <= main_max_year)] # Find the min and max yvar values across the list of yvars and create # separate ColumnDataSource objects for each forecast series (this helps # with the hovertools) main_min_yvar = 100 main_max_yvar = 0 cds_list = [] for k, yvar in enumerate(frcst_var_list): main_min_yvar = np.minimum(main_min_yvar, df_main[yvar].min()) main_max_yvar = np.maximum(main_max_yvar, df_main[yvar].max()) frcst_df = df_full[['year', yvar, yvar + '_frcst']].dropna() frcst_df['frcst'] = frcst_df[yvar + '_frcst'] = 1 frcst_df['frcst_label'] = legend_label_list[k] frcst_df.rename(columns={yvar: 'debt_gdp'}, inplace=True) frcst_df = frcst_df[['year', 'debt_gdp', 'frcst', 'frcst_label']] cds_list.append(ColumnDataSource(frcst_df)) # Output to HTML file fig_title = fig_title_str fig_path = fig_path output_file(fig_path, title=fig_title) fig = figure(title=fig_title, plot_height=600, plot_width=1100, x_axis_label='Year', x_range=(main_min_year - 1, main_max_year + 1), y_axis_label='Percent of Gross Domestic Product', y_range=(main_min_yvar - 5, main_max_yvar + 5), tools=['save', 'zoom_in', 'zoom_out', 'box_zoom', 'pan', 'undo', 'redo', 'reset', 'help'], toolbar_location='left') fig.toolbar.logo = None # Set title font size and axes font sizes fig.title.text_font_size = '15pt' fig.xaxis.axis_label_text_font_size = '12pt' fig.xaxis.major_label_text_font_size = '12pt' fig.yaxis.axis_label_text_font_size = '12pt' fig.yaxis.major_label_text_font_size = '12pt' # Modify tick intervals for X-axis and Y-axis fig.xaxis.ticker = SingleIntervalTicker(interval=10, num_minor_ticks=2) fig.xgrid.ticker = SingleIntervalTicker(interval=10) fig.yaxis.ticker = SingleIntervalTicker(interval=20, num_minor_ticks=2) fig.ygrid.ticker = SingleIntervalTicker(interval=20) min_256_color_ind = 0 max_256_color_ind = 200 intercept = max_256_color_ind slope = (min_256_color_ind - intercept) / (len(frcst_var_list) - 1) legend_item_list = [] for k, v in enumerate(frcst_var_list): color_ind = int(np.round(slope * k + intercept)) line = fig.line(x='year', y='debt_gdp', source=cds_list[k], color=Reds[256][color_ind], line_width=3, alpha=0.7, muted_alpha=0.15) legend_item_list.append((legend_label_list[k], [line])) # Add information on hover tooltips = [('Year', '@year'), ('Debt/GDP','@debt_gdp'), ('Forecast', '@frcst'), ('Forecast date', '@frcst_label')] fig.add_tools(HoverTool(tooltips=tooltips, toggleable=False)) # Add legend legend = Legend(items=legend_item_list, location='center') fig.add_layout(legend, 'right') fig.legend.border_line_width = 1 fig.legend.border_line_color = 'black' fig.legend.border_line_alpha = 1 fig.legend.label_text_font_size = '4mm' # Set legend muting click policy fig.legend.click_policy = 'mute' # Add notes below image for note_text in note_text_list: caption = Title(text=note_text, align='left', text_font_size='4mm', text_font_style='italic') fig.add_layout(caption, 'below') return fig
plot_width=1200, x_axis_label='Year', x_range=(min_year, max_year), y_axis_label='Percent of Gross Domestic Product', y_range=(0, max_debt + 20), toolbar_location=None) # Set title font size and axes font sizes fig.title.text_font_size = '18pt' fig.xaxis.axis_label_text_font_size = '12pt' fig.xaxis.major_label_text_font_size = '12pt' fig.yaxis.axis_label_text_font_size = '12pt' fig.yaxis.major_label_text_font_size = '12pt' # Modify tick intervals for X-axis and Y-axis fig.xaxis.ticker = SingleIntervalTicker(interval=10, num_minor_ticks=0) fig.xgrid.ticker = SingleIntervalTicker(interval=20) fig.yaxis.ticker = SingleIntervalTicker(interval=25, num_minor_ticks=0) fig.ygrid.ticker = SingleIntervalTicker(interval=50) # Plotting the data line fig.varea(x='year', y1='debt', y2=0, source=debt_cds, color='#C584DB') # Vertical line showing start of forecast data fig.segment(x0=2021, y0=0, x1=2021, y1=300, color='gray', line_dash='6 2', line_width=2)
def Zancada(DatosBokeh, EjeX, MetricasAuxiliares): """ GRAFICO DISCRETO | LONGITUD DE ZANCADA """ # Creacion del diccionario de metricas auxiliares DiccionarioVariables = ParametrosVariables(DatosBokeh) # Generacion del codigo JavaScript que habilita la visualizacion de metricas auxiliares CodigoJS = GeneracionCodigoJS(MetricasAuxiliares) # Asignacion de tamaño del punto en graficas discretas SizeCircle = FunctionSizeCircle(DatosBokeh) # Creacion de un grafica PLT = figure(width=1000, height=400, x_range=(DatosBokeh.data[EjeX].min(), DatosBokeh.data[EjeX].max()), y_range=(LimiteEjeY(DatosBokeh, 'LONGITUD ZANCADA', 'Inferior'), LimiteEjeY(DatosBokeh, 'LONGITUD ZANCADA', 'Superior')), tools='', toolbar_location=None) # Inclusion de datos PLT.circle(EjeX, 'LongitudZancada[m]', source=DatosBokeh, size=SizeCircle, line_color=transform( 'LongitudZancada[m]', LinearColorMapper(palette=PaletaColoresLinea, low=0.8, high=2)), color=transform( 'LongitudZancada[m]', LinearColorMapper(palette=PaletaColores, low=0.8, high=2)), fill_alpha=1) PLT_Linea = PLT.line(EjeX, 'LongitudZancada[m]', source=DatosBokeh, color='white', line_width=0, line_alpha=0) PLT.add_tools( HoverTool(tooltips=[('', '@{LongitudZancada[m]}{0,0.00} m')], renderers=[PLT_Linea], mode='vline')) # Inclusion de lineas auxiliares ListadoMetricasAuxiliares = {} for Metrica in MetricasAuxiliares: if DiccionarioVariables[Metrica]['Tipo'] == 'circle': ListadoMetricasAuxiliares[ 'l' + str(MetricasAuxiliares.index(Metrica))] = PLT.circle( EjeX, DiccionarioVariables[Metrica]['Variable'].split('[', 1)[0] + DiccionarioVariables['LONGITUD ZANCADA']['Sufijo'], source=DiccionarioVariables[Metrica]['CDS'], size=SizeCircle, line_color=DiccionarioVariables[Metrica]['Color'], color=DiccionarioVariables[Metrica]['Color'], **DiccionarioVariables[Metrica]['Propiedades']) elif DiccionarioVariables[Metrica]['Tipo'] == 'step': ListadoMetricasAuxiliares[ 'l' + str(MetricasAuxiliares.index(Metrica))] = PLT.step( EjeX, DiccionarioVariables[Metrica]['Variable'].split('[', 1)[0] + DiccionarioVariables['LONGITUD ZANCADA']['Sufijo'], source=DiccionarioVariables[Metrica]['CDS'], color=DiccionarioVariables[Metrica]['Color'], **DiccionarioVariables[Metrica]['Propiedades']) else: ListadoMetricasAuxiliares[ 'l' + str(MetricasAuxiliares.index(Metrica))] = PLT.line( EjeX, DiccionarioVariables[Metrica]['Variable'].split('[', 1)[0] + DiccionarioVariables['LONGITUD ZANCADA']['Sufijo'], source=DiccionarioVariables[Metrica]['CDS'], color=DiccionarioVariables[Metrica]['Color'], **DiccionarioVariables[Metrica]['Propiedades']) # Atributos PLT.title.text = 'LONGITUD DE ZANCADA' PLT.sizing_mode = 'fixed' PLT.yaxis.axis_label = 'Longitud de zancada [m]' PLT.yaxis.formatter = NumeralTickFormatter(format='0.0') PLT.grid.visible = False PLT.yaxis.minor_tick_line_color = None # Asignacion de opciones de visualizacion del eje X if EjeX == 'Distancia[m]': PLT.xaxis.axis_label = 'Distancia' PLT.xaxis.formatter = NumeralTickFormatter(format='0') if DatosBokeh.data['Distancia[m]'].max() >= 4000: PLT.xaxis.ticker = SingleIntervalTicker(interval=1000) PLT.xaxis.major_label_overrides = FormateoEjes( DatosBokeh.data['Distancia[m]'], 1000, 1000, 0, 0) elif EjeX == 'TiempoActividad': PLT.xaxis.axis_label = 'Tiempo actividad' PLT.xaxis.formatter = DatetimeTickFormatter(hourmin='%H:%M:%S', minutes='%M:%S', seconds='%Ss') PLT.xaxis.ticker = DatetimeTicker() elif EjeX == 'TiempoTotal': PLT.xaxis.axis_label = 'Tiempo total' PLT.xaxis.formatter = DatetimeTickFormatter(hourmin='%H:%M:%S', minutes='%M:%S', seconds='%Ss') PLT.xaxis.ticker = DatetimeTicker() #Botones Botones = CheckboxGroup(labels=MetricasAuxiliares, active=[], width=100, height=380) ListadoMetricasAuxiliares['checkbox'] = Botones CodigoJSFrecuenciaCardiaca = CustomJS(code=CodigoJS, args=ListadoMetricasAuxiliares) Botones.js_on_click(CodigoJSFrecuenciaCardiaca) #Layout GridBotones = layout( [Spacer(width=100, height=25), Column(Botones, width=100, height=375)], sizing_mode='fixed', width=100, height=400) GridGrafica = gridplot([PLT, GridBotones], ncols=2, sizing_mode='stretch_width', toolbar_location=None, plot_width=1100, plot_height=400) return GridGrafica
un_hover = HoverTool(tooltips=[ ("Name", "@name"), ("Population", "@totpop"), ("Unemployment Rate", "@unemprate{1.11%}"), ("(Long, Lat)", "($x, $y)") ], renderers=[un_patches]) unemprate.add_tools(un_hover) unemprate.grid.grid_line_color = None unemprate.hover.point_policy = "follow_mouse" unemprate.circle(x=barclays_x, y=barclays_y, size=10, line_color="black", fill_color="silver", line_width=0.5) # making scroll active by default poverty.toolbar.active_scroll = poverty.select_one(WheelZoomTool) fsrate.toolbar.active_scroll = fsrate.select_one(WheelZoomTool) unemprate.toolbar.active_scroll = unemprate.select_one(WheelZoomTool) # making a legend pov_color_bar = ColorBar(color_mapper=LinearColorMapper(palette=pov_palette, low=0, high=11), ticker=SingleIntervalTicker(interval=1), title="Population in poverty (%)", label_standoff=12, width=220, orientation="horizontal", border_line_color=None, location=(0,0)) unemp_color_bar = ColorBar(color_mapper=LinearColorMapper(palette=unemp_palette, low=0, high=7), ticker=SingleIntervalTicker(interval=.5), title="Unemployment rate (%)", label_standoff=12, width=220, orientation="horizontal", border_line_color=None, location=(0,0)) fs_color_bar = ColorBar(color_mapper=LinearColorMapper(palette=fs_palette, low=0, high=13), ticker=SingleIntervalTicker(interval=1), title="Food Stamps/SNAP use (%)", label_standoff=12, width=220, orientation="horizontal", border_line_color=None, location=(0,0)) # adding the label on barclays and legend below each map poverty.add_layout(pov_color_bar, 'below') unemprate.add_layout(unemp_color_bar, 'below') fsrate.add_layout(fs_color_bar, 'below') poverty.add_layout(barclays_label1) fsrate.add_layout(barclays_label2) unemprate.add_layout(barclays_label3)
y=barclays_y, size=10, line_color="black", fill_color="silver", line_width=0.5) # making scroll active by default poverty.toolbar.active_scroll = poverty.select_one(WheelZoomTool) fsrate.toolbar.active_scroll = fsrate.select_one(WheelZoomTool) unemprate.toolbar.active_scroll = unemprate.select_one(WheelZoomTool) # making a legend pov_color_bar = ColorBar(color_mapper=LinearColorMapper(palette=pov_palette, low=-1.5, high=2), ticker=SingleIntervalTicker(interval=0.5), title="Change in Poverty (%) from 2011 to 2016", label_standoff=12, width=220, orientation="horizontal", border_line_color=None, location=(0, 0)) unemp_color_bar = ColorBar( color_mapper=LinearColorMapper(palette=unemp_palette, low=-1.5, high=3), ticker=SingleIntervalTicker(interval=0.5), title="Change in Unemployment rate (%) from 2011 to 2016", label_standoff=12, width=220, orientation="horizontal", border_line_color=None,
def gen_one_tseries(tseries_var, hover_descr='yvar', df=main_df, start_year='min', end_year='max', note_text_list=[], fig_title_str='', fig_path='', line_color='blue'): """ This function creates a plot of a single time series from the set of variables from the outlays.csv dataset. """ # Create Variables for min and max values if start_year == 'min': min_year = df['year'].min() else: min_year = int(start_year) if end_year == 'max': max_year = df['year'].max() else: max_year = int(end_year) df_main = df[(df['year'] >= min_year) & (df['year'] <= max_year)] min_yvar = df_main[tseries_var].min() max_yvar = df_main[tseries_var].max() buffer_pct_yvar = 0.1 buffer_yvar = buffer_pct_yvar * (max_yvar - min_yvar) # Create column data source for visualization cds = ColumnDataSource(df_main) # Output to HTML file fig_title = fig_title_str fig_path = fig_path output_file(fig_path, title=fig_title) fig = figure(title=fig_title, plot_height=600, plot_width=1100, x_axis_label='Year', x_range=(min_year - 1, max_year + 1), y_axis_label='Percent of Gross Domestic Product', y_range=(min_yvar - buffer_yvar, max_yvar + buffer_yvar), toolbar_location=None) # Set title font size and axes font sizes fig.title.text_font_size = '15pt' fig.xaxis.axis_label_text_font_size = '12pt' fig.xaxis.major_label_text_font_size = '12pt' fig.yaxis.axis_label_text_font_size = '12pt' fig.yaxis.major_label_text_font_size = '12pt' # Modify tick intervals for X-axis and Y-axis fig.xaxis.ticker = SingleIntervalTicker(interval=5, num_minor_ticks=5) fig.xgrid.ticker = SingleIntervalTicker(interval=5) if tseries_var == 'tot_nonint_outlays_gdp': fig.yaxis.ticker = SingleIntervalTicker(interval=2, num_minor_ticks=2) fig.ygrid.ticker = SingleIntervalTicker(interval=2) elif tseries_var == 'mand_outlays_pct_tot_nonint': fig.yaxis.ticker = SingleIntervalTicker(interval=5, num_minor_ticks=1) fig.ygrid.ticker = SingleIntervalTicker(interval=5) fig.line(x='year', y=tseries_var, source=cds, color=line_color, line_width=4, alpha=0.7) fig.circle(x='year', y=tseries_var, source=cds, color=line_color, size=7, line_width=1, line_color='black', fill_color=line_color, alpha=0.7) # Add information on hover tooltips = [('Year', '@year'), (hover_descr, '@' + tseries_var + '{0.0}'+'%')] hover_glyph = fig.circle(x='year', y=tseries_var, source=cds, size=10, alpha=0, hover_fill_color='gray', hover_alpha=0.5) fig.add_tools(HoverTool(tooltips=tooltips)) # Turn off scrolling fig.toolbar.active_drag = None # Add notes below image for note_text in note_text_list: caption = Title(text=note_text, align='left', text_font_size='4mm', text_font_style='italic') fig.add_layout(caption, 'below') return fig
def bokeh_pi_ticks(fig, interval, axis='x'): if axis == 'x': fig.xaxis.ticker = SingleIntervalTicker(interval=interval) fig.xaxis.formatter = pi_formatter()
y_axis_label='pdf f(t|df)', y_range=(y_min, y_max), toolbar_location=None) # Output to HTML file output_file(fig_path, title=fig_title) # Set title font size and axes font sizes fig.title.text_font_size = '15.5pt' fig.xaxis.axis_label_text_font_size = '12pt' fig.xaxis.major_label_text_font_size = '12pt' fig.yaxis.axis_label_text_font_size = '12pt' fig.yaxis.major_label_text_font_size = '12pt' # Modify tick intervals for X-axis and Y-axis fig.xaxis.ticker = SingleIntervalTicker(interval=10, num_minor_ticks=1) # fig.xgrid.ticker = SingleIntervalTicker(interval=10) # fig.xaxis.major_label_overrides = dict(zip([0, t_i], ['0', '|t_i|'])) fig.yaxis.ticker = SingleIntervalTicker(interval=0.1, num_minor_ticks=2) fig.ygrid.ticker = SingleIntervalTicker(interval=10) # Plotting the line fig.line(x='t_stat_vals', y='t_dist_vals', source=t_cds, color='black', line_width=3) # Create vertical dotted line at 0 fig.segment(x0=0, y0=0,