示例#1
0
def layout():

    date_select = DateRangeSlider(name="period",
                                  title="Period:",
                                  value=(start, end),
                                  bounds=(bounds_start, bounds_end),
                                  value_labels='show',
                                  range=(dict(days=1), None))
    date_select.on_change('value', on_date_change)

    country_select = Select(title="Host Site Country:",
                            value="World",
                            options=country_choices)
    country_select.on_change('value', on_country_change)

    controls = VBoxModelForm(_children=[
        Paragraph(text="Date Range"),
        Paragraph(text=""),  # spacing hack
        Paragraph(text=""),
        date_select,
        country_select
    ])

    vboxsmall = VBoxModelForm(_children=[controls, source_par])
    #hbox1 = HBox(children=[job_loc_plot_builder(), vboxsmall])
    #hbox2 = HBox(children=[weekday_builder(), jobtype_builder()])
    #layout = VBox(children=[hbox1, hbox2])
    layout = VBox(children=[vboxsmall])

    return layout
示例#2
0
    def assemble_precision_recall_tab(self):
        dropdown_value = self.model_dropdown.value
        threshold_value = self.threshold_slider.value
        precision_and_recall = self.daily_precision_and_recall_for_threshold(
            threshold_value, self.model_probas[dropdown_value],
            self.test_labels)
        daily_metrics = self.daily_metrics[dropdown_value]
        vis_x_axis = daily_metrics.index
        min_date, max_date = vis_x_axis.min(), vis_x_axis.max()

        time_period_slider = DateRangeSlider(title="Time Period",
                                             value=(min_date, max_date),
                                             start=min_date,
                                             end=max_date,
                                             step=1)

        precision_recall_f = figure(plot_width=700,
                                    plot_height=400,
                                    x_axis_type="datetime",
                                    title=dropdown_value)

        precision_recall_f.xaxis.axis_label = "Date"
        precision_recall_f.yaxis.axis_label = "Precision"

        prec_source = ColumnDataSource(precision_and_recall["precision"])
        rec_source = ColumnDataSource(precision_and_recall["recall"])

        precision_recall_f.line("date",
                                "precision",
                                source=prec_source,
                                color="orange",
                                legend="Precision")
        precision_recall_f.line("date",
                                "recall",
                                source=rec_source,
                                color="green",
                                legend="Recall")

        precision_recall_f.legend.location = "bottom_right"

        def update(attr, old, new):
            model = self.model_dropdown.value
            threshold = self.threshold_slider.value
            date_start, date_end = time_period_slider.value_as_datetime
            precision_recall_f.title.text = model
            precision_and_recall = self.daily_precision_and_recall_for_threshold(
                threshold, self.model_probas[model], self.test_labels)
            prec_metrics = precision_and_recall["precision"][
                date_start:date_end]
            recall_metrics = precision_and_recall["recall"][
                date_start:date_end]
            prec_source.data = ColumnDataSource.from_df(prec_metrics)
            rec_source.data = ColumnDataSource.from_df(recall_metrics)

        self.model_dropdown.on_change('value', update)
        time_period_slider.on_change('value', update)
        self.threshold_slider.on_change('value', update)

        layout = column(time_period_slider, precision_recall_f)
        return layout
示例#3
0
def Create_Range_Sliders():

    range_slider_x = RangeSlider(title='X-Axis Range',
                                 start=0,
                                 end=1,
                                 value=(0, 1),
                                 step=0.1)
    range_slider_y = RangeSlider(title='Y-Axis Range',
                                 start=0,
                                 end=1,
                                 value=(0, 1),
                                 step=0.1)
    range_slider_xdate = DateRangeSlider(title='X-Axis Range (Date)',
                                         start=date(2017, 1, 1),
                                         end=date(2017, 1, 2),
                                         value=(date(2017, 1,
                                                     1), date(2017, 1, 2)),
                                         step=1)
    range_slider_ydate = DateRangeSlider(title='Y-Axis Range (Date)',
                                         start=date(2017, 1, 1),
                                         end=date(2017, 1, 2),
                                         value=(date(2017, 1,
                                                     1), date(2017, 1, 2)),
                                         step=1)

    return (range_slider_x, range_slider_y, range_slider_xdate,
            range_slider_ydate)
示例#4
0
def layout():

    date_select = DateRangeSlider(
        name="period",
        title="Period:",
        value=(start, end),
        bounds=(bounds_start, bounds_end),
        value_labels='show',
        range=(dict(days=1), None))
    date_select.on_change('value', on_date_change)

    country_select = Select(title="Host Site Country:", value="World",
                            options=country_choices)
    country_select.on_change('value', on_country_change)

    controls = VBoxModelForm(_children=[Paragraph(text="Date Range"),
                                        Paragraph(text=""),  # spacing hack
                                        Paragraph(text=""),
                                        date_select, country_select])

    vboxsmall = VBoxModelForm(_children=[controls, source_par])
    #hbox1 = HBox(children=[job_loc_plot_builder(), vboxsmall])
    #hbox2 = HBox(children=[weekday_builder(), jobtype_builder()])
    #layout = VBox(children=[hbox1, hbox2])
    layout = VBox(children=[vboxsmall])

    return layout
示例#5
0
def plot(df, feauture):
    def create_plot(source,country, feauture):
        hover = HoverTool(tooltips=[("Date", "@date{%F}"), (feauture, str('@'+feauture))],
                      formatters = {'@date':'datetime'})
        p = figure(plot_width=900, plot_height=500,x_axis_type="datetime",
                   title="Total Covid-19 {} in {} by date".format(feauture, country),
                    toolbar_location='above')
        p.line(x='date', y=feauture, line_width=1, source=source,
               line_color="black")
        p.vbar(x='date', top=feauture, line_width=1, source=source, fill_color='orange', hover_fill_color='grey',
               hover_fill_alpha=1)

        p.add_tools(hover)
        p.xaxis.axis_label = 'Date'
        p.yaxis.axis_label = 'Number of {}'.format(feauture)
        p.axis.axis_label_text_font_style = 'bold'
        p.yaxis.formatter = NumeralTickFormatter(format = '0.0a')
        p.background_fill_color = "beige"

        return p

    def update(attr, old, new):
        country = country_select.value
        new_df = df[df['location'] == country]
        start = datetime.fromtimestamp(date_select.value[0] / 1000)
        end = datetime.fromtimestamp(date_select.value[1] / 1000)
        new_df = new_df[new_df['date'] >= start]
        new_df = new_df[new_df['date'] <= end]
        new_src = ColumnDataSource(new_df)
        source.data.update(new_src.data)
        p.title.text = 'Total covid-19 {} in {}'.format(feauture, country)




    countries = list(df['location'].unique())

    country_select = Select(title = 'Country', value = 'world', options = countries)
    country_select.on_change('value', update)

    date_select = DateRangeSlider(title = 'Date Range', start = min(df['date']), end = max(df['date']),
                              value = (min(df['date']), max(df['date'])), step = 15)
    date_select.on_change('value', update)

    initial_country = country_select.value
    source = ColumnDataSource(df[df['location'] == initial_country])

    p = create_plot(source, initial_country, feauture)

    controls = Column(country_select, date_select)

    layout = row(controls, p)
    return layout
def build_widgets_wb(stock_list):
    # CODE SECTION: setup widgets, widgetbox name = controls_wb
    WIDGET_WIDTH = 250

    # ========== Select Stocks ============= #
    select_stk_1 = Select(width = WIDGET_WIDTH, title='Select Stock 1:', value = stock_list[0], options=stock_list)
    select_stk_2 = Select(width = WIDGET_WIDTH, title='Select Stock 2:', value = stock_list[0], options=stock_list)

    # ========== Strategy Type ============= #
    strategy_list = ['kalman', 'distance', 'cointegration']
    select_strategy = Select(width = WIDGET_WIDTH, title='Select Strategy:', value = strategy_list[0], options=strategy_list)

    # ========== set start/end date ============= #
    # date time variables
    MAX_START = date(2014, 1, 1)
    MAX_END = date(2018, 12, 30)
    DEFAULT_START = date(2016, 5, 1)
    DEFAULT_END = date(2016, 12, 31)
    STEP = 1

    backtest_dates = DateRangeSlider(width = WIDGET_WIDTH, 
                                     start=MAX_START, end=MAX_END, 
                                     value=(DEFAULT_START, DEFAULT_END), 
                                     step=STEP, title="Backtest Date Range:")

    start_bt = Button(label="Backtest", button_type="success", width = WIDGET_WIDTH)

    # controls = column(select_stk_1, select_stk_2, select_strategy, backtest_dates, start_bt)
    controls_wb = widgetbox(select_stk_1, select_stk_2, select_strategy, backtest_dates, start_bt, width=600)
    return controls_wb
示例#7
0
def date_slider(p, *, dates=None, date_column='dt'):
    # todo a bit crap, but kinda works.. not sure what's the proper way?
    # maybe they aren't computed before show()??
    # p.x_range.on_change('start', lambda attr, old, new: print("Start", new))
    # p.x_range.on_change('end', lambda attr, old, new: print("End", new))

    if dates is None:
        graphs = p.renderers
        # todo autodetect by type instead of name?
        dts = np.concatenate([g.data_source.data[date_column] for g in graphs])
        # FFS... apparently no easier way
        sdate = pd.Timestamp(np.min(dts)).to_pydatetime()
        edate = pd.Timestamp(np.max(dts)).to_pydatetime()
    else:
        sdate = min(dates)
        edate = max(dates)
    # todo not sure if should use today?
    edate += timedelta(days=5)

    from bokeh.models.widgets import DateRangeSlider  # type: ignore
    ds = DateRangeSlider(
        title="Date Range: ",
        start=sdate,
        end=edate,
        value=(sdate, edate),
        step=1,
    )
    from bokeh.models import CustomJS  # type: ignore

    # TODO hmm. so, js won't be able to call into python in Jupyter...
    # see https://docs.bokeh.org/en/latest/docs/gallery/slider.html
    update_js = CustomJS(args=dict(ds=ds, xrange=p.x_range),
                         code=J('''
    const [ll, rr] = ds.value;
    // didn't work??
    // xrange.set({"start": ll, "end": rr})
    xrange.start = ll;
    xrange.end   = rr;

    // todo hmm, turned out it wasn't necessary??
    // source.trigger('change');
    '''))

    # todo add some quick selectors, e.g. last month, last year, etc like plotly
    ds.js_on_change('value', update_js)
    return ds
示例#8
0
文件: main.py 项目: q-rai/WasteKnox
def source_filters(sources):
    def _handle_state_filter():
        for fullname in sources['dataframes']:
            df = sources['dataframes'][fullname]
            df = df[(df.index >= _state['date_range'][0]) & (df.index <= _state['date_range'][1])]
            units = UNIT_CONVERSION_MAP[_state['units']]
            df = df * UNIT_CONVERSION[units]
            sources['sources'][fullname].data = ColumnDataSource(df).data

        for callback in ELEMENT_CALLBACKS:
            callback(sources=sources, **_state)

    def _date_slider_handler(attr, old, new):
        start_time, end_time = new
        start_date = dt.datetime.fromtimestamp(start_time / 1000)
        end_date = dt.datetime.fromtimestamp(end_time / 1000)
        _state['date_range'] = (start_date, end_date)
        _handle_state_filter()

    start_date = dt.datetime(year=2018, month=12, day=1)
    end_date = dt.datetime(year=2018, month=12, day=1)
    date_slider = DateRangeSlider(start=_state['date_range'][0], end=_state['date_range'][1], value=_state['date_range'], step=1, title="Date Range", height=100)
    date_slider.on_change('value', _date_slider_handler)

    def _radio_button_group_handler(attr, old, new):
        _state['units'] = int(new)
        _handle_state_filter()

    radio_button_group = RadioButtonGroup(labels=UNIT_CONVERSION_MAP, active=0, width=700, height=100)

    radio_button_group.on_change('active', _radio_button_group_handler)

    div_button_group_selection = Div(text=f'<img src="/visualization/static/images/{UNIT_CONVERSION_MAP[_state["units"]]}.svg" height="100px"/>', height=100)

    def _update_div_button_group(**kwargs):
        units = UNIT_CONVERSION_MAP[kwargs['units']]
        div_button_group_selection.text = f'<img src="/visualization/static/images/{units}.svg" height="100px"/>'
    ELEMENT_CALLBACKS.append(_update_div_button_group)

    return [date_slider, radio_button_group, div_button_group_selection]
示例#9
0
def sentiment_viz():
    #Imports
    import mysql.connector
    import sqlalchemy as db
    import pandas as pd 
    from bokeh.plotting import figure, output_file, show
    from bokeh.models.widgets import DateRangeSlider,TextInput,Dropdown
    from bokeh.models.widgets.inputs import AutocompleteInput
    from bokeh.models import Panel, Tabs
    from bokeh.layouts import column
    from bokeh.embed import components
    import numpy as np
    import datetime
    #query mysql for article data and aggregate by day
    con = db.create_engine('mysql+mysqlconnector://*******************')
    df = pd.read_sql('SELECT * FROM articles', con=con)
    df['publishedAt'] = pd.to_datetime(df['publishedAt'])
    df['date_only']=df['publishedAt'].apply(lambda x: x.date())
    dailycounts=df.groupby(by='date_only').agg({'preds':['count','mean']})
    dailycounts.columns=['volume','sentiment_net']
    dailycounts['date'] = dailycounts.index
    publist = df['source_name'].unique().tolist() 
    pollist = [] #pd.read_sql('SELECT * FROM politicians',con=con)
    
    #Sentiment Valence Chart
    pnet = figure(plot_width=1000, plot_height=300, x_axis_type='datetime')
    pnet.toolbar.logo = None
    pnet.toolbar_location = None
    pnet.background_fill_color = "lavender"
    #News Volume Chart
    pvol = figure(plot_width=1000, plot_height=100, x_axis_type='datetime')
    pvol.toolbar.logo = None
    pvol.toolbar_location = None
    pvol.background_fill_color = "bisque"

   #Render data lines
    pnet.line(dailycounts['date'], 
       dailycounts['sentiment_net'], 
       line_width=2,
      color='purple')
    pvol.line(dailycounts['date'], 
       dailycounts['volume'], 
       line_width=2,color='orange')
    #Menu objects
    polmenu = AutocompleteInput(completions=pollist,title='Politician (case sensitive)')
    pubmenu = AutocompleteInput(completions=publist,title='Publication (case sensitive)')
    date_slider = DateRangeSlider(start=min(dailycounts['date']), end=max(dailycounts['date']), 
                          value=(min(dailycounts['date']),max(dailycounts['date'])), step=1, title="Date Range")
    #create components to be rendered in html
    script,div = components(column(pnet,pvol,polmenu,pubmenu,date_slider))
    print(dailycounts.head())
    return script,div
示例#10
0
    def month_range_options(self):
        """Returns gridplot (bokeh layout or Element) defining elements for the User to manipulate Data shown in
        other views.

            Function first checks if the months variables are initialized and if not, initializes them. Then one
            bokeh widget - DateRangeSlider is created.

            DateRangeSlider will allow User to filter data to Months between two "borders" of the Slider. Even though
            DateRangeSlider defines step: 1 (so all days from the months are shown), formatter applied will only show
            month-year values ("%b-%Y).
            Additionally, defined callback checks months of start-stop values and compares them to months from
            old values. This way, callbacks aren't triggered for every slight change in the Slider and change in
            .chosen_months is only triggered when the actual change in months happens.

            Values for the Slider are also taken from instance attributes - this way User's previous choice is
            remembered and can be shown upon coming back to Settings View.

            Returns DateRangeSlider.
        """

        if self.is_month_range_initialized is False:
            self.__initialize_months()

        sld = DateRangeSlider(start=self.all_months[0], end=self.all_months[-1], step=1,
                              value=(self.chosen_months[0], self.chosen_months[-1]),
                              format="%b-%Y", title="Chosen Month Range: ",
                              css_classes=["month_range_slider"])

        def month_range_callback(attr, old, new):
            formatting = "%Y-%m"
            old_str = self.__create_timetuple_string_from_timestamp(old, formatting)
            new_str = self.__create_timetuple_string_from_timestamp(new, formatting)
            if old_str != new_str:
                self.__update_chosen_months(new)

        sld.on_change("value", month_range_callback)

        return sld
示例#11
0
def bokeh_main_2():
    import sys
    src = Path(__file__).absolute().parent / 'src'
    sys.path.insert(0, str(src))

    from bokeh.layouts import layout  # type: ignore
    from bokeh.models.widgets import Tabs, Panel  # type: ignore
    from bokeh.plotting import figure  # type: ignore

    from dashboard.core.bokeh import test_scatter_matrix
    import holoviews as hv
    f1 = hv.render(test_scatter_matrix())

    f2 = figure()
    f2.circle([0, 0, 2], [4, -1, 1])

    # todo need something more lazy?
    from dashboard.data import sleep_dataframe
    from dashboard.sleep import plot_sleep
    # TODO would be cool to display logs in the frontend and also currently evaluated function?
    # although pehaps it's easier to just always keep logs open?

    from bokeh.models.widgets import DateRangeSlider  # type: ignore
    from datetime import date
    drs = DateRangeSlider(
        title="Date Range: ",
        start=date(2017, 1, 1),
        end=date.today(),
        value=(date(2017, 9, 7), date(2017, 10, 15)),
        step=1,
    )

    def update(attr, old, new):
        print(attr, old, new)

    from bokeh.models import CustomJS  # type: ignore
    # todo see https://docs.bokeh.org/en/latest/docs/gallery/slider.html
    update_js = CustomJS(args=dict(drs=drs),
                         code='''
console.log("HIIII");
''')

    drs.on_change('value', update)
    drs.js_on_change('value', update_js)

    l1 = layout([[f1, drs]], sizing_mode='fixed')
    l2 = layout([[f2]], sizing_mode='fixed')
    tabs = Tabs(tabs=[
        Panel(child=l1, title='This is Tab 1'),
        Panel(child=l2, title='This is Tab 2'),
        # Panel(child=layout([[sp]]), title='Sleep dataframe'),
    ])

    curdoc().add_root(tabs)
示例#12
0
    def assemble_global_widgets(self):
        model_menu = [(self.rf_clf.__name__, self.rf_clf.__name__), None,
                      (self.xgb_clf.__name__, self.xgb_clf.__name__)]

        model_dropdown = Dropdown(label="Model",
                                  button_type="warning",
                                  menu=model_menu,
                                  value=self.xgb_clf.__name__)

        vis_x_axis = self.test
        min_date, max_date = vis_x_axis.index.min(), vis_x_axis.index.max()

        time_period_slider = DateRangeSlider(title="Time Period",
                                             value=(min_date, max_date),
                                             start=min_date,
                                             end=max_date,
                                             step=1)

        return model_dropdown, time_period_slider
示例#13
0
    p.title.text = 'Covid-19 Cases and Deaths for ' + sel_country.value + ': ' + sel_chart.value
    src.data.update(new_src.data)
    p.extra_y_ranges['Avg'].start = 0.95 * np.min(
        [src.data['avgc'], src.data['avgd']])
    p.extra_y_ranges['Avg'].end = 1.05 * np.max(
        [src.data['avgc'], src.data['avgd']])


# set up the controls
sel_country = Select(value="India", options=sorted_by_cases, width=220)
sel_chart = Select(value='Day by Day',
                   options=['Day by Day', 'Cumulative'],
                   width=120)
dateslider = DateRangeSlider(start=datemin,
                             end=datemax,
                             value=(datemin, datemax),
                             title='Date Range',
                             sizing_mode="scale_width")

# set up the event handlers
sel_chart.on_change('value', update)
sel_country.on_change('value', update)
dateslider.on_change('value', update)

# create the dataset and the plot
src = make_dataset(sel_country.value,
                   sel_chart.value,
                   range_start=datemin,
                   range_end=datemax)
p = make_plot(src)
示例#14
0
    for (i=0; i<source.data.date.length; i++){
        if (!source.data.offset_applied[i]){
            source.data.date[i] = source.data.date[i] - utcOffset;
        }
    }
    console.log(source.data);

""")
data_src.js_on_change('stream', source_js_callback)

btn = Button(label='Update')
btn.on_click(update_data_src)

date_widget = DateRangeSlider(
    title='Date Range',
    value=DT_RANGE,
    start=DT_RANGE[0],
    end=DT_RANGE[1],
)


def source_py_callback(attr, old, new):
    if not len(data_src.data['date']):
        return
    min_dt = min(data_src.data['date'])
    max_dt = max(data_src.data['date'])
    date_widget.start = min_dt
    date_widget.end = max_dt
    date_widget.value = (min_dt, max_dt)


data_src.on_change('data', source_py_callback)
words_not_in_vocab = PreText(text='Query words not in vocab: ' +
                             ', '.join(key_list_nonvocab_words))
relevance_threshold = Slider(title="relevance threshold",
                             value=0.5,
                             start=0,
                             end=1,
                             step=0.01)
app_select = Select(title='Select app:', value=app_names[0], options=app_names)
limit_to_keyword = TextInput(title="limit to reviews containing the word:",
                             value='')

reviews = PreText(text='', width=1000)
#date_range = RangeSlider(title="Select range of dates", start = 1, end = len(unique_dates), step=1, value=(1, len(unique_dates)), width=1000)
date_range = DateRangeSlider(title="Select range of dates",
                             start=unique_dates[0],
                             end=unique_dates[-1],
                             step=1,
                             value=(unique_dates[0], unique_dates[-1]),
                             width=1000)
update_printed_reviews_button = Button(
    label="Get relevant reviews in selected timeframe", button_type="success")


def update_app(attrname, old, new):

    app_name = app_select.value
    unique_dates = unique_dates_dict[app_name]

    #just to reset the slider
    date_range.start = unique_dates[0]
    date_range.end = unique_dates[-1]
    date_range.value = (unique_dates[0], unique_dates[-1])
示例#16
0
                   value=0,
                   step=10)
cp_btnGroup = RadioButtonGroup(name="cp_btngroup",
                               labels=["less than", "disable", "greater than"],
                               active=1,
                               margin=(0, 0, 20, 0))
cp_slider = Slider(
    title="Closing Price Change Ratio (%)",
    start=-100,
    end=100,
    value=0,
    step=10,
)
date_range_slider = DateRangeSlider(title="Date range",
                                    value=(date_form(data_date[20]),
                                           date_form(data_date[-20])),
                                    start=date_form(data_date[0]),
                                    end=date_form(data_date[-1]),
                                    step=1)
stock_code_input = TextInput(title="Stock Code")
stock_name_input = TextInput(title="Stock Name")
stock_selector = Select(title="Choose Stock to Plot")

mb_source = ColumnDataSource(data={"date": [], "price": []})
cp_source = ColumnDataSource(data={"date": [], "price": []})

TOOLTIPS = [("Title", "@title"), ("Date", "@date_str"), ("Price", "@price")]
p = figure(x_axis_type="datetime",
           plot_height=500,
           plot_width=600,
           title="",
           toolbar_location=None,
示例#17
0
def first_tab_create(filterData):
    ########method1: create data source for plots

    # dummy data that will be replaced by button values once we get those implemented (right now only granulaity button is implemented)

    all_min_date = filterData.groupby('dataid').agg(min)["time"]
    all_max_date = filterData.groupby('dataid').agg(max)["time"]

    dummy_daterange = ['2019-05-01', '2019-08-20']
    dummy_home_id = 27
    dummy_data_type = 'car1'
    dummy_granularity = '15 Minutes'

    def plot1_data(house, daterange=dummy_daterange, data=dummy_data_type, xaxis=dummy_granularity):

        # house is an integer number ex. 27
        # daterange is an array with 2 strings, start date and end date. ex. ['2019-05-01','2019-08-09']
        # weekdays is an ordered list 0-6 of integers ex. [1,4,6] (these are the days we want to exclude)
        # data is a string ex. 'car1'
        # xaxis is also a string ex. 'hour'

        houseData = filterData[filterData['dataid'] == house].sort_values('time', ascending=True)[[data, 'time']]
        # that cuts the house, sorts by ascending time, and pulls out only the type of data that was requested
        houseData.index = houseData['time']  # reindex by the datetime
        houseData = houseData.loc[daterange[0]:daterange[1], :]  # cut to the days requested

        # Now we get into the xaxis user options #
        if xaxis == '15 Minutes':
            houseData = houseData.drop(columns="time")

        if xaxis == 'Hour':
            houseData = houseData.resample('1h').mean()
            houseData[data]=houseData[data]*3600/3600

        if xaxis == 'Day':
            houseData = houseData.resample('1d').mean()
            houseData[data] = houseData[data] * 3600 / 3600 * 24

        if xaxis == 'Week':
            houseData = houseData.resample('1w').mean()
            houseData[data] = houseData[data] * 3600 / 3600 *24 * 7

        if xaxis == 'Month':
            houseData = houseData.resample('1m').mean()
            houseData[data] = houseData[data] * 3600 / 3600 *24 * 7 * 30 ############this computation is wrong because n stadard month but just go with it for now
        # if none of these, 15 Minutes is implied and passed through
        return ColumnDataSource(houseData)


    def plot2_data(house,daterange=dummy_daterange,weekdays = [],data=dummy_data_type,xaxis=dummy_granularity):
             houseData = filterData[filterData['dataid'] == house].sort_values('time', ascending = True)[[data,'time']]
            #  that cuts the house, sorts by ascending time, and pulls out only the type of data that was requested
             houseData.index = houseData['time'] # reindex by the datetime
             houseData = houseData.loc[daterange[0]:daterange[1],:] # cut to the days requested

             for i in weekdays:
                 houseData = houseData[houseData['time'].dt.dayofweek != i] # cut out days we dont want

             if xaxis == 'avgday':
                 houseData = houseData.resample('1d').sum() ####chjange to mean
                 houseData['time'] = houseData.index
                 houseData = houseData.groupby(houseData['time'].dt.dayofweek)[data].mean()
                 houseData.index = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
                 


             if xaxis == 'avghour':
                 houseData = houseData.resample('1h').mean()
                 houseData['time'] = houseData.index
                 houseData = houseData.groupby(houseData['time'].dt.hour)[data].mean() # Does not account for UTC change!
    

             houseData = pd.DataFrame(data = houseData)
             houseData['axis'] = houseData.index

           
             return ColumnDataSource(houseData) 

    # now we need to set up our plot axis

    ##########method2: create plots

    def plot1_plot(src):
        # create the plot every time  a change occurs
        plot1 = figure(title="Energy Consumption Per Period", x_axis_type="datetime", x_axis_label="Date",
                       y_axis_label="Energy Consumption [kWh]")
        plot1.line('time', "grid", source=src, )  # simple line plot   #data_type_available[data_type_selector.active]

        return plot1  # plot object type

    def plot2_plot(src):
        plot2 = figure(x_range = (0,23), y_range=(-7,2), title='Average Power Consumption For Hours in a Day') # gotta do the ranges as mins and maxes
        plot2.vbar(x='axis', top = 'grid', width=1, source=src) 
        plot2.yaxis.axis_label = 'Power Consumption [kW]'
        plot2.xaxis.axis_label = 'Hour of the Day'
        #plot2 = figure(title = 'PLOT2')
        #plot2.line('axis','grid', source = src)

        return plot2

    #########Method3: Update App

    def update(attr, old, new):  # still a little unsure how the update function gets values passed in implicitly
        # these values to be replaced with button/user inputs

        home_id_to_plot = 27
        daterange_to_plot = ['2019-05-01', '2019-08-20']
        data_type_to_plot = 'grid'
        exclude_days_to_plot = []
        avg_to_plot = 'avghour'


        # home_id_to_plot = int(home_id_selector.value)
        # print(attr, old, new)

        #         if home_id_selector.value == new:

        #             daterange_to_plot = [all_min_date[home_id_to_plot].strftime("%Y-%m-%d"), all_max_date[home_id_to_plot].strftime("%Y-%m-%d")]
        #             date_range_slider.start=all_min_date[home_id_to_plot]
        #             date_range_slider.end=all_max_date[home_id_to_plot]
        #             date_range_slider.value=(all_min_date[home_id_to_plot],all_max_date[home_id_to_plot])

        #             print("if 1 truth")
        #         else:
        daterange_raw = list(date_range_slider.value_as_datetime)
        daterange_to_plot = [daterange_raw[0].strftime("%Y-%m-%d"), daterange_raw[1].strftime("%Y-%m-%d")]
        #         print("falsyy")

        # date_range_slider.update(start=all_min_date[home_id_to_plot], end=all_max_date[home_id_to_plot],
        #                          value=(all_min_date[home_id_to_plot], all_max_date[home_id_to_plot]))

        #         print("after:",new)

        #         print(attr,old,new)

        #         daterange_to_plot=list(string_date1,string_date2)

        #         daterange_to_plot=dummy_daterange

        data_type_to_plot = "grid"  # data_type_available[data_type_selector.active]


        # only working button call so far
        granularity_to_plot = granularity_1.labels[granularity_1.active]

        #         granularity_to_plot= [granularity_1.labels[i] for i in granularity_1.active]
        print("before data create")
        # create a new data source
        new_src1 = plot1_data(home_id_to_plot, daterange=daterange_to_plot, data=data_type_to_plot,
                              xaxis=granularity_to_plot)


        new_src2 = plot2_data(home_id_to_plot, daterange=daterange_to_plot, 
                weekdays=exclude_days_to_plot, data=data_type_to_plot,xaxis=avg_to_plot)


        print("before data update")

        # push new data  to the source data the rest of the app is usig for plot1
    
        src1.data.update(new_src1.data)

        src2.data.update(new_src2.data)

        print("updated data")

    #     def new_home(attr,old,new):
    #         return


      
    ############# Add widgets

    # only the granularity implemented so far
    granularity_1 = RadioGroup(
        labels=["15 Minutes", "Hour", "Day", "Week", "Month"], active=0)

    granularity_1.on_change('active',
                            update)  # not sure exactly how this works but runs update on the change of the button and passes through the value of the button

    home_ids_available = np.unique(filterData['dataid'])

    home_ids_available= list(map(str, home_ids_available))
    home_id_selector = Dropdown(label="Home ID to Plot", button_type="warning", menu=home_ids_available)

    home_ids_available = list(map(str, home_ids_available))
    home_id_selector = Dropdown(label="Home ID to Plot", button_type="warning", menu=home_ids_available, value="27")


    # home_id_selector.on_change('value', update) #############put back in later!!!!1

    date_range_slider = DateRangeSlider(title="Date Range: ", start=date(2019, 5, 1), end=date(2019, 8, 20),
                                        value=(date(2019, 5, 1), date(2019, 8, 20)), step=1, callback_policy = 'mouseup')
    date_range_slider.on_change("value", update)

    # data_type_selector = RadioButtonGroup(labels=["Net Home Consumption","Solar Generation","EV Consumption"],active=0)

    # data_type_selector.on_change('active',update)
    # data_type_available=["grid","solar","car1"]

    ############ Initialize opening plot and data
    src1 = plot1_data(int(home_ids_available[0]), ['2019-05-01', '2019-08-20'], 'grid',
                      '15 Minutes')  # start with a data range we know is correct
    plot1 = plot1_plot(src1)

    src2 = plot2_data(27,['2019-05-01', '2019-08-20'],[],'grid','avghour')
    plot2 = plot2_plot(src2)

    ##### Formatting of the app screen

    # Put controls in a single element (add more later to format)
    controls = WidgetBox(granularity_1, home_id_selector, date_range_slider)  # data_type_selector)

    # Create a row layout

    layout = row(controls, column(plot1,plot2))


    # Make a tab with the layout
    tab = Panel(child=layout, title='First Tab')


    return tab
示例#18
0
def create_tab(data, name):
    def make_dataset(metric_fun, metric_sentiment, month_start, month_end,
                     editorial, category, social_network, product):
        """Constrói os datasets para cada tipo de gráfico utilizado no dashboard

        Parâmetros
        ----------
        data : DataFrame
            Pandas DataFrame expandido com dados do Sprinklr
        metric_fun : FUN
            Função para calcular métrica específica selecionada no widget
        metric_sentiment : str
            Sentimento relacionado à métrica escolhida (Positividade: positivo, Gradiente: negativo, Crise: negativo, Saúde do post: positivo)
        [restante] : str
            Valaores selecionados nas opções de filtros nos widgets 
        Retorna
        -------
        dict
            Dicionário com três chaves, correspondentes aos três gráficos apresentados. Cada chave é relacionada ao nome o gráfico 
            e os valores são datasets no formato column data source
        """
        month_start = pd.Timestamp(month_start)
        month_end = pd.Timestamp(month_end)

        # Filtragem dos dados com base nas seleções dos widgets
        filters = {
            'Editoria': editorial,
            'Categoria': category,
            'SocialNetwork': social_network,
            'Produto': product
        }
        filtered_data = filter_data(data, filters)

        # Gera datasets para cada gráfico
        ts_data = metric_fun(filtered_data)
        ts_data = ts_data[(ts_data.time >= month_start)
                          & (ts_data.time <= month_end)]

        donut_data = filtered_data[(filtered_data.Month >= month_start)
                                   & (filtered_data.Month <= month_end)]
        donut_data = percent(donut_data)
        donut_data['angle'] = donut_data['value'] / sum(
            donut_data['value']) * 2 * pi
        donut_data['color'] = Category20c[donut_data.shape[0]]

        avg_donut_data = percent_avg(filtered_data)
        avg_donut_data = avg_donut_data[avg_donut_data.Month == month_end][[
            'Sentimento', 'MAVG'
        ]]
        avg_donut_data.columns = ['label', 'value']
        avg_donut_data['angle'] = avg_donut_data['value'] / sum(
            avg_donut_data['value']) * 2 * pi
        avg_donut_data['color'] = Category20c[avg_donut_data.shape[0]]

        top_data = filter_sentiment(filtered_data, metric_sentiment)
        top_data = top_data[(top_data.Month >= month_start)
                            & (top_data.Month <= month_end)]
        top_data = brand_health_txengages(top_data)
        avg_top_data = round(top_data.score.mean(), 2)
        top_data = top_data.sort_values('score', ascending=False).iloc[:10]
        top_data = top_data.sort_values('score')
        top_data['recorte'] = [
            '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'
        ]

        # Converte dataframes em column data source
        datasets = {
            'ts': ColumnDataSource(ts_data),
            'donut': ColumnDataSource(donut_data),
            'avg_donut': ColumnDataSource(avg_donut_data),
            'top': ColumnDataSource(top_data),
            'avg_top': avg_top_data
        }

        return datasets

    def update(attr, old, new):
        """Constrói os datasets para cada tipo de gráfico utilizado no dashboard

        Parâmetros
        ----------
        old : ColumnDataSource
            Dataframe antigo relacionado aos filtros antigos
        new : ColumnDataSource
            Dataframe novo, com linhas filtradas de acordo com seleções mais recentes
        """
        month_start = month_select.value_as_date[0]
        month_end = month_select.value_as_date[1]
        editorial = editorial_select.value
        category = category_select.value
        product = product_select.value
        social_network = [
            social_network_select.labels[i]
            for i in social_network_select.active
        ]
        metric = metric_select.value
        metric_attr = get_metric_attr(metric)
        metric_fun = metric_attr['fun']
        metric_sentiment = metric_attr['sentiment']

        new_src = make_dataset(metric_fun=metric_fun,
                               metric_sentiment=metric_sentiment,
                               month_start=month_start,
                               month_end=month_end,
                               editorial=editorial,
                               category=category,
                               social_network=social_network,
                               product=product)
        src['ts'].data.update(new_src['ts'].data)
        src['top'].data.update(new_src['top'].data)
        src['avg_top'] = new_src['avg_top']
        src['donut'].data.update(new_src['donut'].data)
        src['avg_donut'].data.update(new_src['avg_donut'].data)

    networks = data.SocialNetwork.unique().tolist()
    editorials = get_multselect_options(data, 'Editoria')
    categories = get_multselect_options(data, 'Categoria')
    products = get_multselect_options(data, 'Produto')

    month_select = DateRangeSlider(start=date(2019, 1, 1),
                                   end=date(2019, 8, 1),
                                   value=(date(2019, 1, 1), date(2019, 8, 1)),
                                   step=1,
                                   format="%b %Y")
    metric_select = Select(value="gradiente",
                           options=[("velocity", "Parâmetro de Crise"),
                                    ("positivity", "Grau de Positividade"),
                                    ("gradiente", "Grau de Negatividade"),
                                    ("brand_health", "Saúde da Marca"),
                                    ("post_health", "Saúde do Post")])
    product_select = MultiSelect(value=['Todos'], options=products)
    category_select = MultiSelect(value=['Todos'], options=categories)
    editorial_select = MultiSelect(value=['Todos'], options=editorials)
    social_network_select = CheckboxGroup(labels=networks,
                                          active=list(range(len(networks))))

    metric_select.on_change('value', update)
    month_select.on_change('value', update)
    editorial_select.on_change('value', update)
    category_select.on_change('value', update)
    product_select.on_change('value', update)
    social_network_select.on_change('active', update)

    initial_metric_attr = get_metric_attr(metric_select.value)
    metric_sentiment = initial_metric_attr['sentiment']
    initial_networks = [
        social_network_select.labels[i] for i in social_network_select.active
    ]

    src = make_dataset(metric_fun=initial_metric_attr['fun'],
                       metric_sentiment=metric_sentiment,
                       month_start=month_select.value_as_date[0],
                       month_end=month_select.value_as_date[1],
                       editorial=editorial_select.value,
                       category=category_select.value,
                       social_network=initial_networks,
                       product=product_select.value)

    p_ts = make_plot_ts(src['ts'], 'Evolução', metric_sentiment)
    p_top = make_dotplot(src['top'])
    avg_top = src['avg_top']
    avg_top = create_div_title(f'Escore Médio: {avg_top}')
    p_donut = make_plot_donut(src['donut'], 'Percentual')
    p_avg_donut = make_plot_donut(src['avg_donut'], 'Norma Percentual')

    metric_title = create_div_title('MÉTRICA')
    month_title = create_div_title('PERÍODO')
    network_title = create_div_title('REDE SOCIAL')
    category_title = create_div_title('CATEGORIA')
    editorial_title = create_div_title('EDITORIA')
    product_title = create_div_title('PRODUTO')

    controls = WidgetBox(
        column(metric_title,
               metric_select,
               Div(height=5),
               month_title,
               month_select,
               Div(height=5),
               editorial_title,
               editorial_select,
               Div(height=5),
               category_title,
               category_select,
               Div(height=5),
               product_title,
               product_select,
               Div(height=5),
               network_title,
               social_network_select,
               width=250))

    plots = column(p_ts, Div(height=20), row(p_donut, p_avg_donut))
    layout = row(controls, Div(width=50), plots)
    layout = column(Div(text="", height=5), layout, Div(width=20), avg_top,
                    p_top)
    tab = Panel(child=layout, title=name)

    return tab
示例#19
0
    pdict['active'] = radio_button_group.active
    completed.text = '<b>Update Completed!</b>'


sdate_input = TextInput(value="2020-01-03 00:00:00",
                        title="Start Date: (YYYY-MM-DD HH:MM:SS)")
#sdate_input.on_change("value", my_slider_handler)

edate_input = TextInput(value="2020-01-03 01:00:00",
                        title="End Date: (YYYY-MM-DD HH:MM:SS)")
#edate_input.on_change("value", my_slider_handler)

date_range_slider = DateRangeSlider(title="Data Filter Date Range: ",
                                    start=datetime.datetime(2020, 1, 3, 0),
                                    end=datetime.datetime(2020, 3, 20, 1),
                                    value=(datetime.datetime(2020, 1, 3, 0),
                                           datetime.datetime(2020, 1, 3, 1)),
                                    format="%x,%X")

date_range_start = TextInput(
    value="2020-01-03 00:00:00",
    title="Data Filter Start Date: (YYYY-MM-DD HH:MM:SS)")
#sdate_input.on_change("value", my_slider_handler)

date_range_end = TextInput(value="2020-01-03 01:00:00",
                           title="Data Filter End Date: (YYYY-MM-DD HH:MM:SS)")

idle_range_slider = DateRangeSlider(title="Idle Date Range: ",
                                    start=datetime.datetime(2020, 1, 3, 0),
                                    end=datetime.datetime(2020, 3, 20, 1),
                                    value=(datetime.datetime(2020, 1, 3, 0),
示例#20
0
source_wed = ColumnDataSource(data=dict(time=[], y_value=[]))
source_thu = ColumnDataSource(data=dict(time=[], y_value=[]))
source_fri = ColumnDataSource(data=dict(time=[], y_value=[]))
source_sat = ColumnDataSource(data=dict(time=[], y_value=[]))
source_sun = ColumnDataSource(data=dict(time=[], y_value=[]))

# Create Input controls
station_name = Select(title="Select station",
                      value="Varsapuistikko",
                      options=stations_names)
y_axis = Select(title="Y Axis",
                options=sorted(axis_map.keys()),
                value="empty_slots")
date_range_slider = DateRangeSlider(title="Date Range: ",
                                    start=min_date,
                                    end=max_date,
                                    value=(min_date, max_date),
                                    step=1)

p = figure(x_axis_type="datetime",
           plot_height=300,
           plot_width=500,
           title="",
           tools="",
           toolbar_location=None)
p_mon = figure(plot_height=200,
               plot_width=400,
               toolbar_location=None,
               tools="")
p_tue = figure(plot_height=200,
               plot_width=400,
示例#21
0
#sdate_input.on_change("value", my_slider_handler)

edate_input = TextInput(value="2020-01-03 01:00:00",
                        title="End Date: (YYYY-MM-DD HH:MM:SS)")
#edate_input.on_change("value", my_slider_handler)
count_threshold = TextInput(value="1", title="Count Threshold Value")

resolution_slider = Slider(start=1,
                           end=15,
                           value=7,
                           step=1,
                           title="Hex Resolution")

sdate_range_slider = DateRangeSlider(title="Date Range: ",
                                     start=datetime.datetime(2019, 8, 15, 0),
                                     end=datetime.datetime(2020, 4, 28, 1),
                                     value=(datetime.datetime(2020, 1, 3, 1),
                                            datetime.datetime(2020, 1, 3, 2)),
                                     format="%x,%X")

#sdate_range_slider = DateRangeSlider(title="Date Range: ", start=datetime.datetime(2017, 1, 1,1), end=datetime.datetime(2017, 2, 7,2), value=(datetime.datetime(2017, 9, 7,1), datetime.datetime(2017, 9, 7,2)),format="%Y-%m-%d %H")
#sdate_range_slider = DateRangeSlider(title="Date Range: ", start=datetime.datetime(2017, 1, 1,1), end=datetime.datetime(2017, 2, 7,2), value=(datetime.datetime(2017, 9, 7,1), datetime.datetime(2017, 9, 7,2)),step=1)
#sdate_range_slider.on_change("value", my_slider_handler)
#sdate_range_slider = DateSlider(title="Date Range: ", start=datetime.datetime(2017, 1, 1,1), end=datetime.datetime(2019, 9, 7,2), value=(datetime.datetime(2017, 9, 7,1), datetime.datetime(2017, 9, 7,2)), step=1)

sMindate = datetime.datetime(2020, 1, 3, 0)

Mindate = datetime.datetime(2019, 8, 15, 0)

date_text = Div(text='<b style="color:black">' + str(Mindate) +
                '&nbsp;&nbsp;&nbsp;to&nbsp;&nbsp;&nbsp;' +
                str(Mindate + timedelta(hours=6)) + '<br></b>',
示例#22
0
                     width=100,
                     height=50,
                     orientation='vertical',
                     button_type='primary')
save_button.on_click(save_png_callback)

grid = gridplot(children=[
    word_barplots,
],
                toolbar_location=None,
                merge_tools=True)

date_range_slider = DateRangeSlider(
    start=data['time'].iloc[0],
    end=data['time'].iloc[-1],
    value=(data['time'].iloc[0], data['time'].iloc[-1]),
    format='%d/%m@%H:%M',
    step=1,
    width=95 * (len(word_barplots) - 1) - 40,  # padded
    bar_color='purple')

play_button = Button(label='Run', width=75, button_type='success')
play_button.on_click(update)

bottom_layout = Row(children=[
    date_range_slider,
    play_button,
])

svg_layout = Row(svg_div, width=450, height=380)

arroba_layout = Row(children=[
示例#23
0
def select_values_2(attr, old, new, w_box, c_data):
    if new != 'None':
        if c_data[w_box.children[1].
                  value][new].values.dtype == 'object':  # categorical data
            level_3 = MultiSelect(title='value',
                                  value=['None'],
                                  options=['None'],
                                  width=180)
            try:
                level_3.options = np.unique(
                    c_data[w_box.children[1].value]
                    [new].iloc[:, 0].dropna().values).tolist()
                level_3.value = [level_3.options[0]]
            except TypeError:
                level_3.options = np.unique([
                    str(obj) for obj in c_data[w_box.children[1].value]
                    [new].iloc[:, 0].dropna().values
                ]).tolist()
            finally:
                w_box.children[3] = column(level_3)

        elif 'datetime' in str(c_data[w_box.children[1].value]
                               [new].values.dtype):  # datetime data
            start = c_data[w_box.children[1].value][new].min().dt.date.item()
            end = c_data[w_box.children[1].value][new].max().dt.date.item()
            date_slider = DateRangeSlider(
                title="",
                start=start,
                end=end,
                value=(start, end),
                # value_as_date=True,
                # step=1,
                width=180)
            checkbox_group = CheckboxGroup(labels=["invert selection"],
                                           active=[],
                                           width=180)
            w_box.children[3] = column(date_slider, checkbox_group)

        elif 'int' in str(c_data[w_box.children[1].value][new].values.dtype) or \
                'float' in str(c_data[w_box.children[1].value][new].values.dtype):
            # print("3   ", clinical_data[select_1.value][new].values.dtype)
            start = c_data[w_box.children[1].value][new].min().item()
            end = c_data[w_box.children[1].value][new].max().item()
            slider = RangeSlider(start=start,
                                 end=end,
                                 step=0.1,
                                 value=(start, end),
                                 title=new + " Range",
                                 width=180)
            checkbox_group = CheckboxGroup(labels=["invert selection"],
                                           active=[],
                                           width=180)
            w_box.children[3] = column(slider, checkbox_group)

        else:
            print(
                "Something went wrong, unexpected datatype by clinical data value selecting"
            )  # TODO error message?

    else:
        w_box.children[3] = PreText(text='please select a property', width=200)
示例#24
0
    Div
        Elemento do tipo Div do Bokeh
    """
    text = f'<b><font size=2 color="#00004C">{title}</font></b>'
    div = Div(text=text)
    return div


networks = data.SocialNetwork.unique().tolist()
editorials = get_multselect_options('Editoria')
categories = get_multselect_options('Categoria')
products = get_multselect_options('Produto')

month_select = DateRangeSlider(start=date(2019, 1, 1),
                               end=date(2019, 9, 1),
                               value=(date(2019, 1, 1), date(2019, 9, 1)),
                               step=1,
                               format="%b %Y")

metric_select = Select(title="Métrica:",
                       value="velocity",
                       options=[("velocity", "Parâmetro de Crise"),
                                ("positivity", "Grau de Positividade"),
                                ("gradiente", "Grau de Negatividade"),
                                ("brand_health", "Saúde da Maca"),
                                ("post_health", "Saúde do Post")])

product_select = MultiSelect(value=['Todos'], options=products)
category_select = MultiSelect(value=['Todos'], options=categories)
editorial_select = MultiSelect(value=['Todos'], options=editorials)
social_network_select = CheckboxGroup(labels=networks,
示例#25
0
    def build(self):

        # init widget
        if self.has_type == True:
            active = [i for i in range(len(self.labels))]
            labels = [
                self.labels[i] + " (" + self.colors[i] + ")"
                for i in range(len(self.labels))
            ]
            self.label_checkbox = CheckboxGroup(labels=labels, active=active)

        self.x_rangeslider = RangeSlider(value=[-100, 150],
                                         start=-100,
                                         end=150,
                                         step=1,
                                         title="x")
        self.y_rangeslider = RangeSlider(value=[-100, 100],
                                         start=-100,
                                         end=100,
                                         step=1,
                                         title="y")

        if self.has_time == True:
            self.time_rangeslider = DateRangeSlider(
                format="%Y-%b-%d %H:%M",
                value=[self.timeRange[0], self.timeRange[1]],
                start=self.timeRange[0],
                end=self.timeRange[1],
                step=10,
                title="time")

        controls = []
        if self.has_type == True:
            controls.append(self.label_checkbox)
        controls.append(self.x_rangeslider)
        controls.append(self.y_rangeslider)
        if self.has_time == True:
            controls.append(self.time_rangeslider)
        widgets = widgetbox(controls, width=700, height=700)

        # if self.has_type == True:
        # 	widgets = widgetbox(self.label_checkbox, self.x_rangeslider, self.y_rangeslider, width=700, height=700)
        # 	controls = [self.label_checkbox, self.x_rangeslider, self.y_rangeslider]
        # else:
        # 	widgets = widgetbox(self.x_rangeslider, self.y_rangeslider, width=700, height=700)
        # 	controls = [self.x_rangeslider, self.y_rangeslider]

        for control in controls:

            if type(control) == CheckboxGroup:
                control.on_change('active',
                                  lambda attr, old, new: self.update())
            else:
                control.on_change('value',
                                  lambda attr, old, new: self.update())

        # self.source_scatter is variable which figure will display the data from
        self.source_scatter = ColumnDataSource(data=self.original_data)

        self.scatter_plot = figure(plot_width=700,
                                   plot_height=700,
                                   tools=self.tools,
                                   tooltips=self.tooltip,
                                   toolbar_location="left",
                                   title="")
        sp = self.scatter_plot.circle(x='x',
                                      y='y',
                                      size=20,
                                      color=self.color,
                                      source=self.source_scatter)

        table_attr_name = self.attr_name[:-1]
        st_table = selection_table(table_attr_name, sp, self.source_scatter)

        layout = column(row(widgets, self.scatter_plot), st_table.table)

        self.update()
        for name in self.attr_name:
            self.source_scatter.data[name] = pd.Series(
                self.source_scatter.data[name])

        curdoc().add_root(layout)
示例#26
0
states_select2.on_change('active', update)
states_select3 = CheckboxGroup(labels=STATES[36:54], active=[])
states_select3.on_change('active', update)
#     states_selection = CheckboxGroup(labels=STATES, active = [0,1])
#     states_selection.on_change('active', update)

thresh_select = Slider(start=0,
                       end=1000,
                       step=1,
                       value=0,
                       title='Case Count Minimum')
thresh_select.on_change('value', update)

range_select = DateRangeSlider(start=dt.date(2020, 1, 21),
                               end=dt.date.today(),
                               value=(dt.date(2020, 1, 21), dt.date.today()),
                               step=1,
                               title='Date Range')
range_select.on_change('value', update)

select_all = Button(label="select all")
select_all.on_click(activate_all_update)
unselect_all = Button(label="unselect all")
unselect_all.on_click(deactivate_all_update)

# Initialize source
initial_states = [states_select1.labels[i] for i in states_select1.active] + \
                        [states_select2.labels[i] for i in states_select2.active] + \
                        [states_select3.labels[i] for i in states_select3.active]

src = make_dataset(initial_states,
示例#27
0
    labels = list(labels)
    values = list(values)
    for i in all_gate_names:
        if i not in labels:
            labels.append(i)
            values.append(0)
    zipped = sorted(zip(labels, values))
    labels, values = zip(*zipped)
    labels = np.asarray(labels)
    values = np.asarray(values)
    source.add(values, name=car_type)

date_slider = DateRangeSlider(title='Date Range',
                              start=date(2015, 5, 1),
                              end=date(2016, 5, 30),
                              value=(date(int(start_y), int(start_m),
                                          int(start_d)),
                                     date(int(end_y), int(end_m), int(end_d))),
                              step=1)
color = ['blue', 'red', 'yellow', 'purple', 'cyan', 'black', 'green']


def date_range_update(attrname, old, new):
    """
    Callback for Date Range Slider Interaction.

    All of previous created for the ColumnDataSource
    must be redone in the update in order to correctly
    interact with the graph.
    """
    d1 = datetime.fromtimestamp(date_slider.value[0] / 1000)
示例#28
0
def timeseries_tab(dataframe):
    """
    return a tab showing steps vs time for each person
    """
    def make_dataset(name_list,
                     range_start='2019-01-01',
                     range_end='2019-12-31'):
        """
        Filter the full dataset by name and by date range,
        and return it as a Bokeh ColumnDataSource
        """

        ## why do I have to do this? What is the point of a DateRangeSlider???
        if isinstance(range_start, int):
            range_start = datetime.fromtimestamp(range_start / 1000)
        if isinstance(range_end, int):
            range_end = datetime.fromtimestamp(range_end / 1000)

#        filtered_df = dataframe[name_list].loc[range_start: range_end]
        filtered_df = dataframe.loc[range_start:range_end]

        source = ColumnDataSource(filtered_df)
        return source

    def style(p):
        # Title
        p.title.align = 'center'
        p.title.text_font_size = '20pt'
        p.title.text_font = 'serif'

        # Axis titles
        p.xaxis.axis_label_text_font_size = '14pt'
        p.xaxis.axis_label_text_font_style = 'bold'
        p.yaxis.axis_label_text_font_size = '14pt'
        p.yaxis.axis_label_text_font_style = 'bold'

        # Tick labels
        p.xaxis.major_label_text_font_size = '12pt'
        p.yaxis.major_label_text_font_size = '12pt'

        return p

    def make_plot(source):
        """
        create a Bokeh figure with the selected data
        """
        names_to_plot = source.column_names[1:]

        time_series = figure(x_axis_type="datetime",
                             plot_width=700,
                             plot_height=550)
        hover = HoverTool(tooltips=[("Name", "$name"), ("Date", "@Date{%F}"),
                                    ("Steps", "$y")],
                          formatters={'Date': 'datetime'})
        time_series = style(time_series)
        time_series.add_tools(hover)
        time_series.legend.location = "top_left"
        for i, name in enumerate(names_to_plot):
            time_series.line("Date",
                             name,
                             source=source,
                             line_color=Category20_16[i],
                             line_width=2,
                             name=name,
                             legend_label=name)
        return time_series

    def update(attr, old, new):
        """
        Update data source when something is changed.
        """
        name_list = [name_selection.labels[i] for i in name_selection.active]
        new_src = make_dataset(name_list, date_slider.value[0],
                               date_slider.value[1])
        cds.data.update(new_src.data)

    def update_lines(attr, old, new):
        """
        Hide selected lines
        """
        names_to_plot = [
            name_selection.labels[i] for i in name_selection.active
        ]
        for name in names:
            if name in names_to_plot:
                p.select_one({"name": name}).visible = True
            else:
                p.select_one({"name": name}).visible = False

    ### back to the timeseries_tab function
    names = list(dataframe.columns)
    names.sort()

    # widgets to allow user to configure the plot
    name_selection = CheckboxGroup(labels=names,
                                   active=list(range(len(names))))

    name_selection.on_change('active', update_lines)

    date_slider = DateRangeSlider(title="Date range",
                                  start=date(2019, 1, 1),
                                  end=date(2019, 12, 31),
                                  value=(date(2019, 1, 1), date(2019, 12, 31)),
                                  step=1)
    date_slider.on_change('value', update)

    initial_names = [name_selection.labels[i] for i in name_selection.active]
    cds = make_dataset(initial_names, date_slider.value[0],
                       date_slider.value[1])
    p = make_plot(cds)

    controls = WidgetBox(name_selection, date_slider)
    layout = row(controls, p)

    tab = Panel(child=layout, title="Time series")
    return tab
示例#29
0
    source.data = source.from_df(df)
    source_static.data = source.data
    one_day_df = get_data_subset((VARS['selected_day'], VARS['selected_day']))
    single_day_source.data = single_day_source.from_df(one_day_df)


#############################
# Initialize interactive widgets before calling first update
#############################
update()

date_selector = DateRangeSlider(title="Select Timeframe",
                                end=VARS['global_end'],
                                start=VARS['global_start'],
                                step=1,
                                value=(
                                    VARS['time_range'][0],
                                    VARS['time_range'][1],
                                ))
single_day_selector = DateSlider(
    title="Select Day",
    end=VARS['global_end'],
    start=VARS['global_start'],
    step=1,
    value=VARS['selected_day'],
)

date_selector.on_change('value', update_time_range)
single_day_selector.on_change('value', update_highlighted_day)

##################################################################
示例#30
0
range_slider = RangeSlider(title="Numerical range",
                           value=[30, 70],
                           start=0,
                           end=100,
                           step=0.5)

date_slider = DateSlider(title="Date",
                         value=date(2014, 1, 1),
                         start=date(2010, 1, 1),
                         end=date(2020, 1, 1),
                         step=1)

date_range_slider = DateRangeSlider(title="Date range",
                                    value=(date(2014, 1,
                                                1), date(2018, 12, 31)),
                                    start=date(2010, 1, 1),
                                    end=date(2020, 1, 1),
                                    step=1)

only_value_slider = Slider(value=50, start=0, end=96, step=5)

no_title_slider = Slider(title=None, value=50, start=0, end=96, step=5)


def color_picker():
    def color_slider(title, color):
        return Slider(title=title,
                      show_value=False,
                      value=127,
                      start=0,
                      end=255,
示例#31
0
p1.line('x', 'y2', source = source, legend="KOSPI200", color = 'grey',alpha = 0.8,
        muted_color = 'grey', muted_alpha = 0.2, line_width=2)
p1.legend.location = "top_left"
p1.legend.click_policy="mute"
p1.add_tools(HoverTool(tooltips=[('Date','@x{%Y-%m-%d}'), ('Port','@y1'), ('BM', '@y2')], 
                                 formatters={'x' : 'datetime'}, 
                                 mode = 'vline',
                                 show_arrow=False, point_policy='follow_mouse'))


p2 = figure(plot_width=1200, plot_height=200, x_range = p1.x_range, x_axis_type="datetime")
p2.varea(x='x', y1 = 'zeros', y2 = 'dd', source = source)

date_slider = DateRangeSlider(title="Date Range: ", 
                              start=ts.index[0],
                              end=ts.index[-1], 
                              value=(ts.index[0], ts.index[-1]), 
                              step=1)

def update_data(attrname, old, new):
    # Get the current slider values
    x_start = datetime.fromtimestamp(date_slider.value[0]/1000)
    x_end = datetime.fromtimestamp(date_slider.value[1]/1000)   
    x_start = pd.to_datetime(x_start)
    x_end = pd.to_datetime(x_end)    
    #print(x_start)
    #print(x_end)
    # Generate new data
    new_df = df[(df['x']>= x_start) & (df['x'] <= x_end)]
    new_df.loc[:,'y1'] = (new_df['y1'].pct_change().fillna(0) + 1).cumprod() * 100
    new_df.loc[:,'y2'] = (new_df['y2'].pct_change().fillna(0) + 1).cumprod() * 100