Esempio n. 1
1
def show(sample_size):
    global session
    global scatter_plot
    global source
    global pie_chart_source
    global line_chart_source
    global slider
    DB.__init__(sample_size)
    min_time = DB.min_time()
    max_time = DB.max_time()
    print min_time
    print min_time
    xs, ys, color, time = DB.get_current()
    xs = [xs[i] for i,v in enumerate(time) if time[i] == min_time]
    ys = [ys[i] for i,v in enumerate(time) if time[i] == min_time]
    color = [color[i] for i,v in enumerate(time) if time[i] == min_time]

    time_dict = Counter(time)
    pie_chart_source = ColumnDataSource(data=ChartMath.compute_color_distribution('x', 'y', 'color', color))
    line_chart_source = ColumnDataSource(data=dict(x=[key for key in time_dict], y=[time_dict[key] for key in time_dict]))
    source = ColumnDataSource(data=dict(x=xs, y=ys, color=color))

    scatter_plot = Figure(plot_height=800,
                          plot_width=1200,
                          title="Plot of Voters",
                          tools="pan, reset, resize, save, wheel_zoom",
                          )

    scatter_plot.circle('x', 'y', color='color', source=source, line_width=0, line_alpha=0.001, fill_alpha=0.5, size=15)
    scatter_plot.patches('x', 'y', source=state_source, fill_alpha=0.1, line_width=3, line_alpha=1)

    scatter_plot.x_range.on_change('end', update_coordinates)
    line_chart = Figure(title="Distribution over Time", plot_width=350, plot_height=350)
    line_chart.line(x='x', y='y', source=line_chart_source)
    pie_chart_plot = Figure(plot_height=350,
                            plot_width=350,
                            title="Voter Distribution",
                            x_range=(-1, 1),
                            y_range=(-1, 1))
    pie_chart_plot.wedge(x=0, y=0, source=pie_chart_source, radius=1, start_angle="x", end_angle="y", color="color")
    slider = Slider(start=min_time, end=max_time, value=min_time, step=1, title="Time")

    slider.on_change('value', update_coordinates)
    h = hplot(scatter_plot, vplot(pie_chart_plot, line_chart))
    vplot(slider, h, width=1600, height=1800)
    session = push_session(curdoc())
    session.show()
    #script = autoload_server(scatter_plot, session_id=session.id)
    session.loop_until_closed()
Esempio n. 2
0
class MapPlot(object):
    def __init__(self):
        self.map_plot = Figure(
            tools="pan,wheel_zoom,tap", toolbar_location="right",
            logo=None, min_border=0, min_border_left=0,
            **get_paris_extent(0.6), # x_range & y_range
            plot_width=1100, plot_height=650)
        self.map_plot.add_tile(tile_source=OSM_TILE_SOURCE)
        self.map_plot_renderer = self.map_plot.patches(
            source=geo_source,
            xs="xs",
            ys="ys",
            line_width=2,
            line_color=None,
            selection_line_color="firebrick",
            nonselection_line_color=None,
            fill_color="colors",
            selection_fill_color="colors",
            nonselection_fill_color="colors",
            alpha=0.85,
            selection_alpha=0.9,
            nonselection_alpha=0.85)
        self.map_plot.axis.visible = None
        self.map_plot_ds = self.map_plot_renderer.data_source
    
    def get_plot(self):
        return self.map_plot
    
    def get_data_source(self):
        return self.map_plot_ds
Esempio n. 3
0
def build_local_uk_tab():

    s3_root = 'https://covid19-bokeh-app.s3.eu-west-2.amazonaws.com'

    la_boundaries_gdf = gpd.read_file(
        f'{s3_root}/data/_geo_data/la_districts_dec19.zip'
    ).loc[:, ['lad19cd', 'lad19nm', 'geometry']]

    # Importing uk local authority data
    la_cases_df = pd.read_csv(f'{s3_root}/data/local_uk.csv')

    # Filter for latest date
    la_cases_latest_df = la_cases_df.loc[la_cases_df.date ==
                                         la_cases_df.date.max()]

    # Import local authority population data
    la_pop_df = pd.read_csv(f'{s3_root}/data/local_authority_populations.csv'
                            ).loc[:, ['code', 'population']]

    # Remove commas and convert to numeric dtype
    la_pop_df['population'] = pd.to_numeric(
        (la_pop_df['population'].str.replace(",", "")))

    # Merge cases and population datasets
    la_cases_latest_df = la_cases_latest_df.merge(la_pop_df,
                                                  left_on="area_code",
                                                  right_on="code",
                                                  how="left")

    # Merge geo-boundaries GeoDataFrame with cases, pop dataset
    la_cases_gdf = la_boundaries_gdf.merge(la_cases_latest_df,
                                           left_on="lad19cd",
                                           right_on="area_code",
                                           how="left")

    # Calculate weekly cases per 100,000
    la_cases_gdf['cases_per_pop'] = (
        100000 * la_cases_gdf['weekly_cases'] /
        la_cases_gdf['population']).fillna(0).astype(int)

    # Convert dataset to GeoJSONDataSource to feed geo-plot
    geosource = GeoJSONDataSource(geojson=la_cases_gdf.to_json())

    # Adding figure and geographical patches from shapefile
    local_uk_geo_plot = Figure(title="Weekly Cases per 100,000",
                               plot_height=500,
                               plot_width=500,
                               name="local_uk_geo_plot",
                               output_backend="webgl")

    # Add linear colour mapper for case density
    mapper = linear_cmap(field_name='cases_per_pop',
                         palette=brewer['YlOrRd'][9][:7][::-1],
                         low=min(la_cases_gdf['cases_per_pop']),
                         high=max(la_cases_gdf['cases_per_pop']))

    # Add local authority patches to figure
    geo_patches = local_uk_geo_plot.patches('xs',
                                            'ys',
                                            source=geosource,
                                            alpha=0.8,
                                            color=mapper)

    # Adding hover tool and tap tool
    hover = HoverTool(
        tooltips=[('Local Authority', '@lad19nm'), (
            'Daily Cases',
            '@new_cases'), ('Population', '@population{0,0}'
                            ), ('Weekly Cases per 100,000', '@cases_per_pop')])

    local_uk_geo_plot.add_tools(hover)
    local_uk_geo_plot.add_tools(TapTool())

    # Adding color bar
    color_bar = ColorBar(color_mapper=mapper['transform'], location=(0, 0))

    local_uk_geo_plot.add_layout(color_bar, 'right')

    # Adding recent trend figure
    area_name = "Wandsworth"
    cases_trend_df = la_cases_df.loc[la_cases_df.area_name == area_name]
    cases_trend_df.date = pd.to_datetime(cases_trend_df.date,
                                         format="%Y-%m-%d")
    ninety_days_back = cases_trend_df.date.max() - timedelta(days=90)
    cases_trend_df = cases_trend_df.loc[
        cases_trend_df.date >= ninety_days_back]
    cases_trend_cds = ColumnDataSource(cases_trend_df)

    cases_trend_plot = Figure(title=f"New Cases in {area_name}",
                              plot_height=500,
                              plot_width=500,
                              name="cases_trend_plot",
                              x_axis_type="datetime")

    cases_trend_plot.line(x='date',
                          y='new_cases',
                          legend="New Cases",
                          source=cases_trend_cds)

    cases_trend_plot.line(x='date',
                          y='weekly_average',
                          line_color="orange",
                          legend="Weekly Average",
                          source=cases_trend_cds)

    cases_trend_hover = HoverTool(tooltips=[('Date', '@date{%F}'),
                                            ('Daily Cases', '@new_cases'),
                                            ('Weekly Average',
                                             '@weekly_average{int}')],
                                  formatters={"@date": "datetime"})

    cases_trend_plot.add_tools(cases_trend_hover)

    def callback(attr, old, new):
        index = geosource.selected.indices[0]
        geojson = json.loads(geosource.geojson)
        area_name = geojson['features'][index]['properties']['area_name']

        # Adding recent trend figure
        cases_trend_df = la_cases_df.loc[la_cases_df.area_name == area_name]
        cases_trend_df.date = pd.to_datetime(cases_trend_df.date,
                                             format="%Y-%m-%d")
        ninety_days_back = cases_trend_df.date.max() - timedelta(days=90)
        cases_trend_df = cases_trend_df.loc[
            cases_trend_df.date >= ninety_days_back]

        cases_trend_cds.data = cases_trend_df

        cases_trend_plot.title.text = f"New Cases in {area_name}"

    geosource.selected.on_change('indices', callback)

    # Add the plots to the current document
    curdoc().add_root(local_uk_geo_plot)
    curdoc().add_root(cases_trend_plot)
    b = pickle.load(f)

patch_source = ColumnDataSource(data=dict(borders_x=b["x"],
                                          borders_y=b["y"],
                                          colors=no_colors,
                                          alpha=alpha,
                                          state_names=state_names,
                                          state_totals=state_totals,
                                          state_drunk=state_drunk,
                                          state_percent=state_percent,
                                          state_percent_sp=state_percent_sp))

patches = fig.patches(xs="borders_x",
                      ys="borders_y",
                      source=patch_source,
                      fill_alpha="alpha",
                      fill_color="colors",
                      line_alpha=0,
                      hover_alpha=.3,
                      line_width=5)

fig.add_tools(
    HoverTool(renderers=[patches],
              tooltips=[("State", "@state_names"), ("Total", "@state_totals"),
                        ("Drunk%", "@state_percent{1.11}" + "%"),
                        ("Speeding%", "@state_percent_sp{1.11}" + "%")]))
select = Select(title="Color States By:",
                value="None",
                options=["None", "Drunk%", "Speeding%"])


def update_color(attrname, old, new):
# Generate a figure container for the field
plot_field = Figure(plot_height=400,
                    plot_width=400,
                    tools=toolset,
                    title="Vector valued function",
                    x_range=[curveintegral_settings.x_min, curveintegral_settings.x_max],
                    y_range=[curveintegral_settings.y_min, curveintegral_settings.y_max]
                    )

# remove grid from plot
plot_field.grid[0].grid_line_alpha = 0.0
plot_field.grid[1].grid_line_alpha = 0.0

# Plot the direction field
plot_field.segment('x0', 'y0', 'x1', 'y1', source=source_segments)
plot_field.patches('xs', 'ys', source=source_patches)
plot_field.circle('x', 'y', source=source_basept, color='blue', size=1.5)
# Plot curve
plot_field.line('x', 'y', source=source_curve, color='black', legend='curve')
# Plot parameter point
plot_field.scatter('x', 'y', source=source_param, color='black', legend='c(t)')
# Plot corresponding tangent vector
plot_field.segment('x0', 'y0', 'x1', 'y1', source=source_param, color='black')
plot_field.patches('xs', 'ys', source=source_param, color='black')

# Generate a figure container for the integral value
plot_integral = Figure(title_text_font_size="12pt",
                       plot_height=200,
                       plot_width=400,
                       title="Integral along curve",
                       x_range=[curveintegral_settings.parameter_min, curveintegral_settings.parameter_max],
Esempio n. 6
0
    b = pickle.load(f)

patch_source = ColumnDataSource(
    data=dict(borders_x=b["x"],
        borders_y=b["y"],
        colors=no_colors,
        alpha=alpha,
        state_names=state_names,
        state_totals=state_totals,
        state_drunk=state_drunk,
        state_percent=state_percent,
        state_percent_sp=state_percent_sp
    )
)

patches = fig.patches(xs="borders_x", ys="borders_y", source=patch_source, fill_alpha="alpha",
                    fill_color="colors", line_alpha=0, hover_alpha=.3, line_width=5)

fig.add_tools(HoverTool(renderers=[patches], tooltips=[("State", "@state_names"),
                                      ("Total", "@state_totals"),
                                      ("Drunk%", "@state_percent{1.11}" + "%"),
                                      ("Speeding%", "@state_percent_sp{1.11}" + "%")]))
select = Select(title="Color States By:", value="None", options=["None", "Drunk%", "Speeding%"])

def update_color(attrname, old, new):
    if select.value == "Drunk%":
        patch_source.data["colors"] = drunk_colors
        patch_source.data["alpha"] = [.3]*len(state_names)
    elif select.value == "Speeding%":
        patch_source.data["colors"] = speeding_colors
        patch_source.data["alpha"] = [.3]*len(state_names)
    else:
# Generate a figure container for the field
plot_field = Figure(
    plot_height=400,
    plot_width=400,
    tools=toolset,
    title="Vector valued function",
    x_range=[curveintegral_settings.x_min, curveintegral_settings.x_max],
    y_range=[curveintegral_settings.y_min, curveintegral_settings.y_max])

# remove grid from plot
plot_field.grid[0].grid_line_alpha = 0.0
plot_field.grid[1].grid_line_alpha = 0.0

# Plot the direction field
plot_field.segment('x0', 'y0', 'x1', 'y1', source=source_segments)
plot_field.patches('xs', 'ys', source=source_patches)
plot_field.circle('x', 'y', source=source_basept, color='blue', size=1.5)
# Plot curve
plot_field.line('x', 'y', source=source_curve, color='black', legend='curve')
# Plot parameter point
plot_field.scatter('x', 'y', source=source_param, color='black', legend='c(t)')
# Plot corresponding tangent vector
plot_field.segment('x0', 'y0', 'x1', 'y1', source=source_param, color='black')
plot_field.patches('xs', 'ys', source=source_param, color='black')

# Generate a figure container for the integral value
plot_integral = Figure(title_text_font_size="12pt",
                       plot_height=200,
                       plot_width=400,
                       title="Integral along curve",
                       x_range=[
Esempio n. 8
0
           'Delta Housing Units': delta_housing_units}

agg_method = Select(title='Aggregation Method', value="Number of Permits", options=list(methods))


# Create Column Data Source that will be used by the plot
source = ColumnDataSource(data=dict(xs=[], ys=[], color=[], alpha=[], value=[]))

hover = HoverTool(tooltips=[
    ("Value", "@value"),
])

p = Figure(plot_height=700, plot_width=700, title="",
           x_range=[-94.9, -94.25], y_range=[38.8, 39.45],
           tools=[hover, 'wheel_zoom', 'reset', 'pan'])
p.patches(xs="xs", ys="ys", source=source, fill_color="color",
          fill_alpha='alpha', line_color=None)


controls = [min_year, max_year, min_permit_cost, max_permit_cost,
            agg_method, permit_type_checkbox, res_non_checkbox]

for control in controls:
    if hasattr(control, 'value'):
        control.on_change('value', update)
    elif hasattr(control, 'active'):
        control.on_change('active', update)

inputs = HBox(VBoxForm(controls), width=300)

update(None, None, None)    # initial load of the data
Esempio n. 9
0


del states["HI"]
del states["AK"]

EXCLUDED = ("ak", "hi", "pr", "gu", "vi", "mp", "as")

state_xs = [states[code]["lons"] for code in states]
state_ys = [states[code]["lats"] for code in states]

state_xs = state_xs[0:5] + state_xs[6:16] + state_xs[17:18] + state_xs[19:31] + state_xs[32:46]
state_ys = state_ys[0:5] + state_ys[6:16] + state_ys[17:18] + state_ys[19:31] + state_ys[32:46]

x = [-100,-80, -70, -125, -100]
y = [30,40,45, 40, 45]
#color = ["blue", "red", "green", "gold", "black"]

source = ColumnDataSource(data=dict(x=state_xs, y=state_ys))
source2 = ColumnDataSource(data=dict(x=latitude, y=longitude, color=colors))

p = Figure(title="US Unemployment 2009", toolbar_location="left",
           plot_width=1100, plot_height=700)


p.patches('x', 'y', source=source, fill_alpha=0.1, line_width=1, line_alpha=0.3)
p.circle('x', 'y', color='color', source=source2, fill_alpha=0.1, line_width=1, line_alpha=0.001, size=3)

curdoc().add_root(HBox(children=[p], width=1100))
session.show()
session.loop_until_closed()
Esempio n. 10
0

def on_slider_change(attr, old, new):
    simplify_tolerance = new
    simplify_features(simplify_tolerance)


# let's read some shapefile metadata
crs = states.crs
simplify_slider = Slider(title='Simplify Tolerance',
                         value=0,
                         start=0,
                         end=1,
                         step=.01)
simplify_slider.on_change('value', on_slider_change)

save_button = Button(label='Save')
save_button.on_click(save_to_shapefile)

p = Figure(plot_height=600,
           plot_width=900,
           x_range=(bounds[0], bounds[2]),
           y_range=(bounds[1], bounds[3]))

polys = p.patches(xs='xs', ys='ys', alpha=0.9, source=geo_source)

controls = HBox(width=p.plot_width, children=[simplify_slider, save_button])
layout = VBox(width=p.plot_width, children=[controls, p])

curdoc().add_root(layout)
Esempio n. 11
0
# convert to strings for tooltip
total = [str(x) for x in total_acc]
perc_drunk = [str(x*100)+"%" for x in perc_drunk]
perc_speeding = [str(x*100)+"%" for x in perc_speeding]

border_source = ColumnDataSource(dict(
        xs=x_vals, 
        ys=y_vals,
        total=total_acc,
        state = us_states.keys(),
        perc_drunk = perc_drunk,
        perc_speeding = perc_speeding
    ))

states = fig.patches("xs", "ys", source=border_source, alpha=.5, line_color="red", hover_color="green", hover_alpha=.8, hover_line_color='black')

speeding_source = ColumnDataSource(dict(
    x=speeding_accidents['x'],
    y=speeding_accidents['y'] ))

drinking_source = ColumnDataSource(dict(
    x=drinking_accidents['x'],
    y=drinking_accidents['y'] ))

other_source = ColumnDataSource(dict(
    x=other_accidents['x'],
    y=other_accidents['y'] ))

fig.circle('x', 'y', source=speeding_source, fill_color="red", size=3)
fig.circle('x', 'y', source=drinking_source, fill_color="green", size=3)
Esempio n. 12
0
# output_file("nyc_basemap.html", title="NYC census tracts")
source = ColumnDataSource(
    data=dict(
        QI_colmap=ct_colors, ct_x=ct_x, ct_y=ct_y, NicheScore=qivals, Price=pricevals, Neighborhood=extrainfo["NTAName"]
    )
)  # .loc[recdf.index]
# print source
hover = HoverTool(tooltips=[("Niche Score", "@NicheScore"), ("Price", "@Price")])  # ("Area", "@Neighborhood"),

tools = [PanTool(), BoxZoomTool(), WheelZoomTool(), ResetTool(), hover, PreviewSaveTool()]

p = Figure(title="NicheLife Map", plot_width=800, plot_height=700, tools=tools)
# tools="pan,wheel_zoom,reset,box_zoom,save")  # toolbar_location="top", #box_select,
p.grid.grid_line_alpha = 0

p.patches("ct_x", "ct_y", source=source, fill_color="QI_colmap", fill_alpha=0.7, line_color="white", line_width=0.5)

# image1 = ImageURL(url=source.data["image"], x=-74.04, y=40.85)
# p.add_glyph(source, image1)
p.image_url(url=imageurl, x="-74.04", y="40.85")


# Set up widgets
text = TextInput(title="Map Name", value="NicheLife Map")
feature1 = Slider(title="Subway Accessibility", value=0.5, start=0, end=1, step=0.1)
feature2 = Slider(title="Safety", value=0.5, start=0, end=1, step=0.1)
feature3 = Slider(title="Public Satisfaction", value=0.5, start=0, end=1, step=0.1)
feature4 = Slider(title="Restaurants", value=0.5, start=0, end=1, step=0.1)
feature5 = Slider(title="Grocery Stores", value=0.5, start=0, end=1, step=0.1)
feature6 = Slider(title="Nightlife", value=0.5, start=0, end=1, step=0.1)
price = Select(title="Show Affordability", options=["Yes", "No"])
Esempio n. 13
0
source = ColumnDataSource(
    data=dict(xs=[], ys=[], color=[], alpha=[], value=[]))

hover = HoverTool(tooltips=[
    ("Value", "@value"),
])

p = Figure(plot_height=700,
           plot_width=700,
           title="",
           x_range=[-94.9, -94.25],
           y_range=[38.8, 39.45],
           tools=[hover, 'wheel_zoom', 'reset', 'pan'])
p.patches(xs="xs",
          ys="ys",
          source=source,
          fill_color="color",
          fill_alpha='alpha',
          line_color=None)

controls = [
    min_year, max_year, min_permit_cost, max_permit_cost, agg_method,
    permit_type_checkbox, res_non_checkbox
]

for control in controls:
    if hasattr(control, 'value'):
        control.on_change('value', update)
    elif hasattr(control, 'active'):
        control.on_change('active', update)

inputs = HBox(VBoxForm(controls), width=300)
    def _segment_plot(self, source):
        """Plot showing the mirror segments.

        The plot shows the 91 segment positions with their position number. The colour of the segments indicates how
        long ago they have been recoated.

        Params:
        -------
        source: pandas.DataFrame
            Data source.

        Returns:
        --------
        bokeh.plotting.Figure
            Plot showing the mirror segments.
        """

        def segment_color(date):
            """Fill colour of a mirror segment."""
            days = (datetime.datetime.now().date() - date).days
            days = min(days, self.RECOATING_PERIOD)
            days = max(days, 0)

            def hex_value(v):
                """Convert integer into a hexadecimal string suitable for specifying an RGB value in a css rule."""
                s = format(int(round(255 * v)), 'x')
                if len(s) < 2:
                    s = '0' + s
                return s

            # The colour ranges from dark green for recently recoated segments to white for segments which need to be
            # recoated.
            h = 99
            s = 100
            l = 33 + 67 * days / self.RECOATING_PERIOD
            rgb = colorsys.hls_to_rgb(h / 360, l / 100, s / 100)

            return '#{r}{g}{b}'.format(r=hex_value(rgb[0]),
                                       g=hex_value(rgb[1]),
                                       b=hex_value(rgb[2]))

        plot = Figure(tools='tap', toolbar_location=None)
        colors = [segment_color(d) for d in source.data['ReplacementDate']]
        plot.patches(xs='SegmentPositionCornerXs',
                     ys='SegmentPositionCornerYs',
                     source=source,
                     color=colors,
                     line_color='#dddddd')
        plot.text(x='SegmentPositionX',
                  y='SegmentPositionY',
                  text='SegmentPosition',
                  source=source,
                  text_color='black',
                  text_align='center',
                  text_baseline='middle')

        plot.grid.grid_line_color = None
        plot.axis.visible = False

        plot.min_border_top = 20
        plot.min_border_bottom = 30

        plot.outline_line_color = None

        return plot
Esempio n. 15
0
    geo_source.geojson = states_view.to_json()


def save_to_shapefile():
    states_view.to_file('fout.shp')


def on_slider_change(attr, old, new):
    simplify_tolerance = new
    simplify_features(simplify_tolerance)


# let's read some shapefile metadata
crs = states.crs
simplify_slider = Slider(title='Simplify Tolerance',
                         value=0, start=0, end=1, step=.01)
simplify_slider.on_change('value', on_slider_change)

save_button = Button(label='Save')
save_button.on_click(save_to_shapefile)

p = Figure(plot_height=600, plot_width=900,
           x_range=(bounds[0], bounds[2]), y_range=(bounds[1], bounds[3]))

polys = p.patches(xs='xs', ys='ys', alpha=0.9, source=geo_source)

controls = HBox(width=p.plot_width, children=[simplify_slider, save_button])
layout = VBox(width=p.plot_width, children=[controls, p])

curdoc().add_root(layout)