def callbackselect_state(attr, old, new): try: div_state_pop.text = """<br>Total population of """+select_state.value+": "+f"{state_population_dict[select_state.value]:,d}" except: div_state_pop.text = """<br>Total population of """ + select_state.value + ": Not Available" try: #plot2.vbar(x=demography_age, top=list(demography_data.loc[demography_data['Location'] == select_state.value].values[0][1:-2]), width=0.7) source_bar.data={ 'x': demography_age, 'y': list(demography_data.loc[demography_data['Location'] == select_state.value].values[0][1:-2]) } glyph = VBar(x='x', top='y', bottom=0, width=.8, fill_color="#6599ed") plot2.add_glyph(source_bar, glyph) except: #plot2.vbar(x=demography_age, top=[0,0,0,0,0,0], width=0.7) source_bar.data = { 'x': demography_age, 'y': [0,0,0,0,0,0] } glyph = VBar(x='x', top='y', bottom=0, width=.8, fill_color="#6599ed") plot2.add_glyph(source_bar, glyph) df = gp.get_group(state_name_dict[select_state.value]) date = df['date'] date = pd.to_datetime(date, format='%Y%m%d') positive = df['positive'] negative = df['negative'] recovered = df['recovered'] death = df['death'] positive_increase = df['positiveIncrease'] death_increase = df['deathIncrease'] source1.data={ 'x': date, 'y1': positive, # 'y2' : negative, 'y3': recovered, 'y4': death, 'y5' : positive_increase, 'y6' : death_increase }
plot.axis.visible = False toolStat1 = "pan,box_zoom,wheel_zoom,reset,save" plotStat1 = figure(title="Information content VS performance", sizing_mode='stretch_both', tools = toolStat1, output_backend="webgl", width=650, height=650, toolbar_location="above") plotStat1.xaxis.axis_label = "Information content" plotStat1.yaxis.axis_label = "Performance" #Convert dataframe to datasource linksource = ColumnDataSource(link) source = ColumnDataSource(df) #Draw nodes and lines for go visualiser and statistics plots lines = MultiLine(xs='x', ys='y', line_alpha=0.2, name='edge', line_width=2.5, line_color='darksalmon') edges_r = plot.add_glyph(source_or_glyph=linksource, glyph=lines) if args.models == 2: lines2 = MultiLine(xs='x', ys='y', line_alpha=0.1, name='edge', line_width=2.5, line_color='grey') edges_2 = plot.add_glyph(source_or_glyph=linksource, glyph=lines2) edges_2.visible = False node1 = VBar(x="X", top="Top", bottom="Y", width=0.95, fill_color={'field': 'Score1', 'transform': color_mapper}, name='node1', line_width=0.1, line_color='black', fill_alpha=1) node1_unselected = VBar(x="X", top="Top", bottom="Y", width=0.95, fill_color={'field': 'Score1', 'transform': color_mapper}, name='node1', line_width=0.1, line_color='black', fill_alpha=0.05) nodes1 = plot.add_glyph(source_or_glyph=source, glyph=node1, nonselection_glyph=node1_unselected) node2 = VBar(x="X", top="Y", bottom="Bottom", width=0.95, fill_color={'field': 'Score2', 'transform': color_mapper}, name='node2', line_width=0.1, line_color='black', fill_alpha=1) node2_unselected = VBar(x="X", top="Y", bottom="Bottom", width=0.95, fill_color={'field': 'Score2', 'transform': color_mapper}, name='node2', line_width=0.1, line_color='black', fill_alpha=0.05) nodes2 =plot.add_glyph(source_or_glyph=source, glyph = node2, nonselection_glyph=node2_unselected) color_mapper_diff = LinearColorMapper(palette=cc.coolwarm, low=df['Difference'].min(), high=df['Difference'].max()) color_bar_diff = ColorBar(color_mapper=color_mapper_diff, ticker=BasicTicker(), title='Difference', label_standoff=12, location=(0,0)) node3 = VBar(x="X", top="Top", bottom="Bottom", width=0.95, fill_color={'field': 'Difference', 'transform': color_mapper_diff}, name='node3', line_width=0.1, line_color='black', fill_alpha=1) node3_unselected = VBar(x="X", top="Top", bottom="Bottom", width=0.95, fill_color={'field': 'Difference', 'transform': color_mapper_diff}, name='node3', line_width=0.1, line_color='black', fill_alpha=0.05) nodes3 = plot.add_glyph(source_or_glyph=source, glyph = node3, nonselection_glyph= node3_unselected) nodes3.visible = False taptool = TapTool(renderers=[nodes1, nodes2]) else: node1 = VBar(x="X", top="Top", bottom="Bottom", width=0.95, fill_color={'field': 'Score1', 'transform': color_mapper}, name='node1', line_width=0.1, line_color='black', fill_alpha=1)
def draw_population_map(*, population_file, water_file, islands_file, districts_file, locations, width, height=None, label_font_size, add_legend=False, legend_font_size, legend_padding, legend_spacing, kind, **kwargs): kinds = 'mosaic', 'stacked bar', 'bar' if kind not in kinds: raise ValueError(f'Incorrect type parameter (Must be one of {kinds})') data_ = pd.read_csv(population_file, index_col=0) totals = data_.sum(axis=0) palette = Category10_10[:len(data_)] data_['colors'] = palette groups = [g for g in data_.index] water = gpd.read_file(water_file) water = get_xy(multipolygons_to_polygons(water)) water_src = GeoJSONDataSource(geojson=water.to_json()) islands = gpd.read_file(islands_file) islands = get_xy(multipolygons_to_polygons(islands)) islands_src = GeoJSONDataSource(geojson=islands.to_json()) districts = gpd.read_file(districts_file) districts = get_xy(districts) districts_src = GeoJSONDataSource(geojson=districts.to_json()) fig = figure(**kwargs) fig.grid.grid_line_color = None fig.patches( xs='x', ys='y', source=water_src, fill_color='#59d0ff', fill_alpha=0.8, line_color=None, line_width=0, ) fig.patches( xs='x', ys='y', source=islands_src, fill_color='white', line_color=None, line_width=0, ) fig.patches( xs='x', ys='y', source=districts_src, fill_color=None, line_color='black', line_width=0, ) if kind.lower() == 'mosaic': for col, loc in locations.items(): width = width * np.sqrt(totals[col] / totals.max()) mosaic_data = get_mosaic( data_, data_col=col, x=loc.x, y=loc.y, height=width * np.cos(loc.y * 0.01745), width=width, ) fig.patches(**mosaic_data) if kind.lower() == 'stacked bar': for col, loc in locations.items(): loc_height = height * totals[col] / totals.max() stack_data = get_stacked_bar( data_, data_col=col, x=loc.x, y=loc.y, height=loc_height, width=width, ) fig.patches(**stack_data) if kind.lower() == 'bar': for col, loc in locations.items(): loc_height = height * totals[col] / totals.max() source = ColumnDataSource( get_bar( data_, data_col=col, x=loc.x, y=loc.y, height=loc_height, width=width, )) glyph = VBar( x='x', width=width, top='top', bottom='bottom', fill_color='color', ) fig.add_glyph(source, glyph) labels = LabelSet( x='x', y='top', text='values', text_align='center', text_font_size=label_font_size, source=source, ) fig.add_layout(labels) if add_legend: for group, color in zip(groups, palette): fig.circle(x=[], y=[], size=12, fill_color=color, legend=group) fig.legend.location = 'bottom_left' fig.legend.background_fill_alpha = 1 fig.legend.border_line_color = 'black' fig.legend.label_text_font_size = legend_font_size fig.legend.spacing = legend_spacing fig.legend.padding = legend_padding fig.title.text_font_size = '30px' return fig
N = 9 x = np.linspace(-2, 2, N) y = x**2 source = ColumnDataSource(dict( x=x, top=y, )) plot = Plot(title=None, width=300, height=300, min_border=0, toolbar_location=None) glyph = VBar(x="x", top="top", bottom=0, width=0.5, fill_color="#b3de69") 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 bokehDrawArray(dataFrame, query, figureArray, **kwargs): """ Wrapper bokeh draw array of figures :param dataFrame: - input data frame :param query: - query :param figureArray: - figure array :param kwargs: :return: variable list: * pAll * handle * source * plotArray See example test: RootInteractive/InteractiveDrawing/bokeh/test_bokehDrawSA.py """ options = { 'line': -1, 'size': 2, 'tools': 'pan,box_zoom, wheel_zoom,box_select,lasso_select,reset,save', 'tooltips': [], 'y_axis_type': 'auto', 'x_axis_type': 'auto', 'plot_width': 600, 'plot_height': 400, 'errX': '', 'errY': '', 'commonX': 0, 'commonY': 0, 'ncols': -1, 'layout': '', 'widgetLayout': '', 'palette': Spectral6, "marker": "square", "markers": bokehMarkers, "color": "#000000", "colors": 'Category10', "colorZvar": '', "filter": '', 'doDraw': 0 } options.update(kwargs) dfQuery = dataFrame.query(query) if hasattr(dataFrame, 'metaData'): dfQuery.metaData = dataFrame.metaData logging.info(dfQuery.metaData) # Check/resp. load derived variables i: int for i, variables in enumerate(figureArray): if len(variables) > 1 and variables[0] is not "table": lengthX = len(variables[0]) lengthY = len(variables[1]) length = max(len(variables[0]), len(variables[1])) if len(variables) > 2: optionLocal = options.copy() optionLocal.update(variables[2]) else: optionLocal = options for j in range(0, length): dfQuery, varNameX = pandaGetOrMakeColumn( dfQuery, variables[0][j % lengthX]) dfQuery, varNameY = pandaGetOrMakeColumn( dfQuery, variables[1][j % lengthY]) if ('errY' in optionLocal.keys()) & (optionLocal['errY'] != ''): seriesErrY = dfQuery.eval(optionLocal['errY']) if varNameY + '_lower' not in dfQuery.columns: seriesLower = dfQuery[varNameY] - seriesErrY dfQuery[varNameY + '_lower'] = seriesLower if varNameY + '_upper' not in dfQuery.columns: seriesUpper = dfQuery[varNameY] + seriesErrY dfQuery[varNameY + '_upper'] = seriesUpper if ('errX' in optionLocal.keys()) & (optionLocal['errX'] != ''): seriesErrX = dfQuery.eval(optionLocal['errX']) if varNameX + '_lower' not in dfQuery.columns: seriesLower = dfQuery[varNameX] - seriesErrX dfQuery[varNameX + '_lower'] = seriesLower if varNameX + '_upper' not in dfQuery.columns: seriesUpper = dfQuery[varNameX] + seriesErrX dfQuery[varNameX + '_upper'] = seriesUpper try: source = ColumnDataSource(dfQuery) except: logging.error("Invalid source:", source) # define default options plotArray = [] colorAll = all_palettes[options['colors']] if isinstance(figureArray[-1], dict): options.update(figureArray[-1]) for i, variables in enumerate(figureArray): logging.info(i, variables) if isinstance(variables, dict): continue if variables[0] == 'table': TOptions = {'include': '', 'exclude': ''} if len(variables) > 1: TOptions.update(variables[1]) plotArray.append( makeBokehDataTable(dfQuery, source, TOptions['include'], TOptions['exclude'])) continue xAxisTitle = "" yAxisTitle = "" # zAxisTitle = "" plotTitle = "" for varY in variables[1]: if hasattr(dfQuery, "meta"): yAxisTitle += dfQuery.meta.metaData.get( varY + ".AxisTitle", varY) else: yAxisTitle += varY yAxisTitle += ',' for varX in variables[0]: if hasattr(dfQuery, "meta"): xAxisTitle += dfQuery.meta.metaData.get( varX + ".AxisTitle", varX) else: xAxisTitle += varX xAxisTitle += ',' xAxisTitle = xAxisTitle[:-1] yAxisTitle = yAxisTitle[:-1] plotTitle += yAxisTitle + " vs " + xAxisTitle figureI = figure(plot_width=options['plot_width'], plot_height=options['plot_height'], title=plotTitle, tools=options['tools'], tooltips=options['tooltips'], x_axis_type=options['x_axis_type'], y_axis_type=options['y_axis_type']) figureI.xaxis.axis_label = xAxisTitle figureI.yaxis.axis_label = yAxisTitle # graphArray=drawGraphArray(df, variables) lengthX = len(variables[0]) lengthY = len(variables[1]) length = max(len(variables[0]), len(variables[1])) color_bar = None mapperC = None for i in range(0, length): dfQuery, varNameY = pandaGetOrMakeColumn(dfQuery, variables[1][i % lengthY]) dummy, varNameX = pandaGetOrMakeColumn(dfQuery, variables[0][i % lengthX]) optionLocal = copy.copy(options) optionLocal['color'] = colorAll[max(length, 4)][i] optionLocal['marker'] = optionLocal['markers'][i] if len(variables) > 2: logging.info("Option", variables[2]) optionLocal.update(variables[2]) varX = variables[0][i % lengthX] varY = variables[1][i % lengthY] if (len(optionLocal["colorZvar"]) > 0): logging.info(optionLocal["colorZvar"]) varColor = optionLocal["colorZvar"] mapperC = linear_cmap(field_name=varColor, palette=options['palette'], low=min(dfQuery[varColor]), high=max(dfQuery[varColor])) optionLocal["color"] = mapperC color_bar = ColorBar(color_mapper=mapperC['transform'], width=8, location=(0, 0), title=varColor) # zAxisTitle +=varColor + "," # view = CDSView(source=source, filters=[GroupFilter(column_name=optionLocal['filter'], group=True)]) figureI.scatter(x=varNameX, y=varNameY, fill_alpha=1, source=source, size=optionLocal['size'], color=optionLocal["color"], marker=optionLocal["marker"], legend_label=varY + " vs " + varX) if ('errX' in optionLocal.keys()) & (optionLocal['errX'] != ''): errors = HBar(y=varNameY, left=varNameX + "_lower", right=varNameX + "_upper", line_color=optionLocal["color"]) figureI.add_glyph(source, errors) if ('errY' in optionLocal.keys()) & (optionLocal['errY'] != ''): errors = VBar(x=varNameX, bottom=varNameY + "_lower", top=varNameY + "_upper", line_color=optionLocal["color"]) figureI.add_glyph(source, errors) # errors = Band(base=varNameX, lower=varNameY+"_lower", upper=varNameY+"_upper",source=source) # figureI.add_layout(errors) if color_bar != None: figureI.add_layout(color_bar, 'right') figureI.legend.click_policy = "hide" # zAxisTitle=zAxisTitle[:-1] # if(len(zAxisTitle)>0): # plotTitle += " Color:" + zAxisTitle # figureI.title = plotTitle plotArray.append(figureI) if isinstance(options['layout'], list): pAll = processBokehLayoutArray(options['layout'], plotArray) layoutList = [pAll] else: if len(options['layout']) > 0: # make figure according layout x, layoutList, optionsLayout = processBokehLayout( options["layout"], plotArray) pAll = gridplotRow(layoutList, **optionsLayout) if options['doDraw'] > 0: show(pAll) return pAll, source, layoutList, dfQuery
#source = ColumnDataSource(demography_data.loc[demography_data['Location'] == state]) source_bar = ColumnDataSource(data={ 'x' : demography_age, 'y' : list(demography_data.loc[demography_data['Location'] == state].values[0][1:-2]) }) plot2=figure( title='Agewise distribution of the state', x_axis_label = 'Age of the Population', y_axis_label = 'Percentage of population', x_range=FactorRange(factors=source_bar.data['x']), plot_width=480, plot_height=400, y_range=(0, 1) ) #plot2.vbar(x=demography_age, top=list(demography_data.loc[demography_data['Location'] == state].values[0][1:-2]), width=0.7) glyph = VBar(x='x', top='y', bottom=0, width=.8, fill_color="#6599ed") plot2.add_glyph(source_bar, glyph) print(list(demography_data.loc[demography_data['Location'] == state].values[0][1:-2])) div_head = Div(text="""<h2>US vs states covid-19 spread plots</h2>""", width=500, height=50) div_explain = Div(text="""<h3>US plots(thinner lines and smaller dots) are normalized according to the population of the compared state</h3>""", width=300, height=50) div_us_pop = Div(text="""<br><br><br>Total population of US: """+f"{total_us_population:,d}", width=300, height=50) div_state_pop = Div(text="""<br>Total population of """+state+" : "+f"{state_population_dict[state]:,d}", width=300, height=50) checkbox_group = CheckboxGroup(labels=["positive", "recovered", "death", "positive increase", "death increase"], active=[0,1,2,3,4]) select_state = Select(title="Select State", value="Minnesota", options=states_fullname) #list(list(gp.groups.keys()))) def callbackselect_state(attr, old, new): try: div_state_pop.text = """<br>Total population of """+select_state.value+": "+f"{state_population_dict[select_state.value]:,d}"
fill_alpha=0.8, line_color=None) pltMap.add_glyph(source, pltMapMarker, selection_glyph=pltMapMarkerSelected, nonselection_glyph=pltMapMarker) pltHist = figure(x_range=Range1d(start=1, end=12), tools=int_tools, plot_width=800, plot_height=200) pltHist.xaxis.ticker = df['tx_date'].dt.month.unique() pltHistMarker = VBar(x="x", top="top", bottom="bottom", fill_color="navy", width=1, fill_alpha=0.8, line_color=None) pltHistMarkerSelected = VBar(x="x", top="top", bottom="bottom", fill_color="orange", width=1, fill_alpha=0.8, line_color=None) pltHist.add_glyph(sourceHist, pltHistMarker, selection_glyph=pltHistMarkerSelected, nonselection_glyph=pltHistMarker)