Exemplo n.º 1
0
def build_results_page(ticker_symbol, from_date, to_date):
    ticker_analysis = tsa.TimeSeriesAnalyzer(ticker_symbol, from_date, to_date)
    historical_prices = get_historic_prices_graph(ticker_analysis,
                                                  ticker_symbol)
    stats = get_statistic_results(ticker_analysis)
    distplot_daily_returns = get_distplot_daily_returns(ticker_analysis)
    vol_price_evolution = get_vol_price_evolution(ticker_analysis)
    return [
        dbc.Row(
            dbc.Col(dcc.Graph(id='historical_prices',
                              figure=historical_prices),
                    width=12)),
        dbc.Row([
            dbc.Col([
                dcc.Graph(id='distplot_daily_returns',
                          figure=distplot_daily_returns),
                dcc.Graph(id='vol_price_evolution', figure=vol_price_evolution)
            ],
                    width=8),
            dbc.Col([
                html.H5('Estadísticos del análisis',
                        style=statisticResultsTitles),
                html.Div(children=stats)
            ],
                    width=3)
        ])
    ]
Exemplo n.º 2
0
 def render_content(tab):
     if tab == "tab-1-example":
         return html.Div(
             [
                 html.H3("Tab content 1"),
                 dcc.Graph(
                     id="graph-1-tabs",
                     figure={
                         "data": [{"x": [1, 2, 3], "y": [3, 1, 2], "type": "bar"}]
                     },
                 ),
             ]
         )
     elif tab == "tab-2-example":
         return html.Div(
             [
                 html.H3("Tab content 2"),
                 dcc.Graph(
                     id="graph-2-tabs",
                     figure={
                         "data": [{"x": [1, 2, 3], "y": [5, 10, 6], "type": "bar"}]
                     },
                 ),
             ]
         )
Exemplo n.º 3
0
 def update_output(value):
     if value == 'C':
         return dcc.Graph(id='case_fig', figure=case_fig)
     elif value == 'H':
         return dcc.Graph(id='hos_hos_ts_fig', figure=hos_hos_ts_fig)
     elif value == 'D':
         return dcc.Graph(id='death_fig', figure=death_fig)
Exemplo n.º 4
0
 def _add_plotting_col(self) -> dbc.Col:
     """Add column with plots and tables. It is placed on the right side.
     """
     return dbc.Col(
         id="col-plotting-area",
         children=[
             dbc.Row(  # Passed / failed tests
                 id="row-graph-passed",
                 class_name="g-0 p-2",
                 children=[
                     dcc.Loading(children=[
                         dcc.Graph(id="graph-passed",
                                   figure=self._default_fig_passed)
                     ])
                 ]),
             dbc.Row(  # Duration
                 id="row-graph-duration",
                 class_name="g-0 p-2",
                 children=[
                     dcc.Loading(children=[
                         dcc.Graph(id="graph-duration",
                                   figure=self._default_fig_duration)
                     ])
                 ]),
             dbc.Row(
                 class_name="g-0 p-2",
                 align="center",
                 justify="start",
                 children=[
                     dbc.Col(  # Download
                         width=2,
                         children=[
                             dcc.Loading(children=[
                                 dbc.Button(id="btn-download-data",
                                            children=self._show_tooltip(
                                                "help-download",
                                                "Download Data"),
                                            class_name="me-1",
                                            color="info"),
                                 dcc.Download(id="download-data")
                             ]),
                         ]),
                     dbc.Col(  # Show URL
                         width=10,
                         children=[
                             dbc.Card(id="card-url",
                                      body=True,
                                      class_name="gy-2 p-0",
                                      children=[]),
                         ])
                 ])
         ],
         width=9,
     )
Exemplo n.º 5
0
def UpdateGraph(lap_ids: List[int],
                point_values: List[Text]) -> List[dcc.Graph]:
    if not isinstance(point_values, list):
        point_values = [point_values]
    if lap_ids:
        graphs = []
        laps_data = queries.GetLapsData(lap_ids, point_values)
        for point_value in point_values:
            figure_data = laps_data
            title = point_value
            # Copied so that time_delta can redefine without breaking other graphs.
            if point_value == 'time_delta':
                figure_data = laps_data.copy()
            if point_value == 'racing_line':
                graph_type = 'map'
                fig = px.line_geo(
                    laps_data,
                    title=title,
                    lat='lat',
                    lon='lon',
                    color='lap_id',
                    fitbounds='locations',
                )
            else:
                if point_value == 'time_delta':
                    if len(lap_ids) < 2:
                        continue  # Need at least two laps to make a comparison.
                    figure_data = queries.GetTimeDelta(lap_ids)
                    title = 'time_delta vs first selected lap (lap_id: %s)' % lap_ids[
                        0]
                graph_type = 'graph'
                fig = px.line(figure_data,
                              title=title,
                              x='elapsed_distance_m',
                              y=point_value,
                              color='lap_id',
                              hover_data=['lap_id', 'lap_number', point_value])
                fig.update_xaxes(showspikes=True)
                fig.update_yaxes(fixedrange=True)
                fig.update_layout(hovermode='x unified')
            graph = dcc.Graph(
                {
                    'type': graph_type,
                    'index': point_values.index(point_value)
                },
                figure=fig,
                style={
                    'display': 'inline-grid',
                    'width': '50%'
                })
            graphs.append(graph)
        return graphs
    # Empty line when no rows have been selected.
    return [dcc.Graph(figure=px.line())]
def get_layout(**kwargs):
    return html.Div([
        dcc.Markdown(
            dedent("""
                    # Research Analysis
                    """)),
        dcc.Dropdown(id="app-option",
                     options=[{
                         'label': i,
                         'value': i
                     } for i in get_app_options()],
                     value=get_app_options()[0]),
        dcc.Dropdown(id="balance-option",
                     options=[{
                         'label': i,
                         'value': i
                     } for i in get_balancing_options()],
                     value="Combined"),
        dcc.Loading(id="loading-icon",
                    type="circle",
                    children=[
                        html.Div(
                            children=[dcc.Graph(id="latency_vs_price")],
                            style={'margin': 'auto'},
                        ),
                    ]),
        dcc.Loading(id="loading-icon",
                    type="circle",
                    children=[
                        html.Div(dcc.Graph(id="price_cdf_koss_weights")),
                    ]),
        dcc.Loading(id="loading-icon",
                    type="circle",
                    children=[
                        html.Div(dcc.Graph(id="price_cdf_algo_comparison")),
                    ]),
        dcc.Loading(id="loading-icon",
                    type="circle",
                    children=[
                        html.Div(dcc.Graph(id="latency_cdf_koss_weights")),
                    ]),
        dcc.Loading(id="loading-icon",
                    type="circle",
                    children=[
                        html.Div(dcc.Graph(id="latency_cdf_algo_comparison")),
                    ]),
        # dcc.Loading(
        #     id = "loading-icon",
        #     type="circle",
        #     children=[html.Div(dcc.Graph(id="latecy-to-price-graph"))]
        # ),
    ])
def render_tab_content(active_tab, data):
    """
    This callback takes the 'active_tab' property as input, as well as the
    stored graphs, and renders the tab content depending on what the value of
    'active_tab' is.
    """
    if active_tab and data is not None:
        if active_tab == "scatter":
            return dcc.Graph(figure=data["scatter"])
        elif active_tab == "histogram":
            return dbc.Row([
                dbc.Col(dcc.Graph(figure=data["hist_1"]), width=6),
                dbc.Col(dcc.Graph(figure=data["hist_2"]), width=6),
            ])
    return "No tab selected"
Exemplo n.º 8
0
def test_grbs001_graph_without_ids(dash_dcc, is_eager):
    app = Dash(__name__, eager_loading=is_eager)
    app.layout = html.Div([
        dcc.Graph(className="graph-no-id-1"),
        dcc.Graph(className="graph-no-id-2")
    ])

    dash_dcc.start_server(app)

    assert not dash_dcc.wait_for_element(".graph-no-id-1").get_attribute(
        "id"), "the graph should contain no more auto-generated id"
    assert not dash_dcc.wait_for_element(".graph-no-id-2").get_attribute(
        "id"), "the graph should contain no more auto-generated id"

    assert dash_dcc.get_logs() == []
Exemplo n.º 9
0
def test_grbs004_graph_loading_state_updates(dash_dcc):
    lock = Lock()
    app = Dash(__name__, suppress_callback_exceptions=True)
    app.layout = html.Div(
        [
            html.H1(id="title", children="loading state updates"),
            dcc.Graph(id="my-graph"),
        ]
    )

    @app.callback(Output("my-graph", "figure"), [Input("title", "n_clicks")])
    def update_graph(n_clicks):
        values = [0, n_clicks]
        ranges = [0, n_clicks]

        with lock:
            return {
                "data": [{"x": ranges, "y": values, "line": {"shape": "spline"}}],
            }

    dash_dcc.start_server(app)
    dash_dcc.wait_for_element("#my-graph:not([data-dash-is-loading])")

    with lock:
        title = dash_dcc.wait_for_element("#title")
        title.click()
        dash_dcc.wait_for_element('#my-graph[data-dash-is-loading="true"]')

    dash_dcc.wait_for_element("#my-graph:not([data-dash-is-loading])")

    assert dash_dcc.get_logs() == []
Exemplo n.º 10
0
def updateDismissalMethods(table_data,
						 player,
						 season,
						 match_type,
						 discipline,
						 inter_tav_type):
	if discipline != "Batting": return None
	if not player: return None
	df_batting = pd.DataFrame(table_data)#getBattingDataframe()
	player_name = df_batting.iloc[player[0]]["name"]#df_batting[df_batting['name'] == player]
	df_batting = getBattingDataframe()
	
	df_player = getBattingPlayer(df_batting,
								 player_name,
								 inter_tav_type,
								 season,
								 match_type)

	if df_player.empty: return None

	counter=collections.Counter(df_player['dismissal'].tolist())
	most_common = counter.most_common(6)

	mods = []
	weights = []
	for mod in most_common:
		mods.append(mod[0])
		weights.append(mod[1])	
	return dcc.Graph(figure=getBarChart(mods,weights,bg_colour=True),
		             config={'displayModeBar': False},
		             id='bat-m-graph')
Exemplo n.º 11
0
def updateBowlingDismissalMethods(table_data,
									player,
									 season,
									 match_type,
									 discipline,
									 inter_tav_type):
	if discipline != "Bowling": return None
	if not player: return None	
	df_bowling = pd.DataFrame(table_data)
	player_name = df_bowling.iloc[player[0]]["name"]
	df_bowling = getBowlingDataframe()
	
	df_player = getBowlingPlayer(df_bowling,
								 player_name,
								 inter_tav_type,
								 season,
								 match_type)

	if df_player.empty: return None

	dis_types_df = df_player['dismissal_types'].dropna()
	#print (dis_types)
	mod_list = [item for sublist in dis_types_df.tolist() for item in sublist]
	counter=collections.Counter(mod_list)
	most_common = counter.most_common(6)

	mods = []
	weights = []
	for mod in most_common:
		mods.append(mod[0])
		weights.append(mod[1])	
	return dcc.Graph(figure=getBarChart(mods,weights,bg_colour=True),
		             config={'displayModeBar': False},
		             id='bowl-m-graph')
Exemplo n.º 12
0
def test_grva003_empty_graph(dash_dcc, is_eager):
    app = Dash(__name__, eager_loading=is_eager)

    app.layout = html.Div([
        html.Button(id="click", children="Click me"),
        dcc.Graph(
            id="graph",
            figure={"data": [dict(x=[1, 2, 3], y=[1, 2, 3], type="scatter")]},
        ),
    ])

    @app.callback(
        Output("graph", "figure"),
        [Input("click", "n_clicks")],
        [State("graph", "figure")],
    )
    def render_content(click, prev_graph):
        if click:
            return {}
        return prev_graph

    dash_dcc.start_server(app)
    button = dash_dcc.wait_for_element("#click")
    button.click()
    time.sleep(2)  # Wait for graph to re-render
    dash_dcc.percy_snapshot(
        "render-empty-graph ({})".format("eager" if is_eager else "lazy"))

    assert dash_dcc.get_logs() == []
Exemplo n.º 13
0
def line_plot_multiIndex(df: DataFrame) -> dcc.Graph:
    """
    Returns a line plot for a dataframe with a MultiIndex.
    It is assumed that the first-level index is the real index, and that data should be grouped using the
    second-level one.

    Parameters
    ----------
    df : DataFrame
        Dataframe to plot. It is a multiIndex dataframe.

    Returns
    -------
    g : dcc.Graph
    """
    fig = go.Figure()
    for region in df.index.get_level_values(1).unique():
        fig.add_trace(
            go.Scatter(x=df.index.get_level_values(0).unique(),
                       y=df.loc[(df.index.get_level_values(1) == region),
                                df.columns[0]],
                       name=region))

    fig.update_layout(title=_('Line plot'),
                      xaxis_title=df.index.get_level_values(0).name,
                      yaxis_title=df.columns[0])
    g = dcc.Graph(figure=fig)
    return g
Exemplo n.º 14
0
def generate_funding_chart_progress(funding_data):
    data = json.loads(funding_data)['plans_funding']
    if len(data['plans']) == 0:
        return ''
    trace1 = go.Bar(y=data['total_funded'],
                    x=data['plans'],
                    text=data['percentages'],
                    marker=dict(color='rgb(49,130,189)',
                                line=dict(color='rgb(8,48,107)', width=1.5)),
                    opacity=1,
                    name='Total Funded')

    trace2 = go.Bar(y=data['required'],
                    x=data['plans'],
                    marker=dict(color='#92a8d1',
                                line=dict(color='rgb(8,48,107)', width=1.5)),
                    opacity=0.25,
                    name='Total Required')

    return dcc.Graph(
        id='chart-progress',
        figure={
            'data': [trace1, trace2],
            'layout':
            go.Layout(
                barmode='overlay',
                title=
                'Funding progress for the country\'s emergency plans (Nutrition)'
            )
        })
Exemplo n.º 15
0
def cell_clicked(active_cell):
    if active_cell is None:
        return no_update

    row = active_cell["row_id"]
    print(f"row id: {row}")

    country = df.at[row, "country"]
    print(country)

    col = active_cell["column_id"]
    print(f"column id: {col}")
    print("---------------------")

    y = col if col in ["pop", "gdpPercap"] else "lifeExp"

    fig = px.line(df[df["country"] == country],
                  x="year",
                  y=y,
                  title=" ".join([country, y]))
    fig.update_layout(title={"font_size": 20},
                      title_x=0.5,
                      margin=dict(t=190, r=15, l=5, b=5))
    fig.update_traces(line=dict(color=color[y]))

    return dcc.Graph(figure=fig)
Exemplo n.º 16
0
def get_app2():
    app = dash.Dash(__name__)

    app.layout = html.Div([
        html.Button("i=20", id="button", n_clicks=0),
        DataTable(
            id="table",
            page_size=5,
            columns=[{
                "name": "i",
                "id": "i"
            }, {
                "name": "square",
                "id": "square"
            }],
            data=[{
                "i": i,
                "square": i**2
            } for i in range(50 + 1)],
            page_current=5,
        ),
        dcc.Graph(),
    ])

    @app.callback(Output("table", "data"), Input("button", "n_clicks"))
    def update_table_data(n):
        return ([{
            "i": i,
            "square": i**2
        } for i in range(20 + 1)] if n > 0 else dash.no_update)

    return app
Exemplo n.º 17
0
def test_dvui002_disable_ui_config(dash_duo):
    app = Dash(__name__)
    app.layout = html.Div(
        [
            html.P(id="tcid", children="Hello Disable UI"),
            dcc.Graph(id="broken", animate=3),  # error ignored by disable
        ]
    )

    dash_duo.start_server(
        app,
        debug=True,
        use_reloader=False,
        use_debugger=True,
        dev_tools_hot_reload=False,
        dev_tools_ui=False,
    )

    dash_duo.wait_for_text_to_equal("#tcid", "Hello Disable UI")
    logs = str(wait.until(dash_duo.get_logs, timeout=1))
    assert (
        "Invalid argument `animate` passed into Graph" in logs
    ), "the error should present in the console without DEV tools UI"

    assert not dash_duo.find_elements(
        ".dash-debug-menu"
    ), "the debug menu icon should NOT show up"
    dash_duo.percy_snapshot("devtools - disable dev tools UI - no debug menu")
Exemplo n.º 18
0
def test_grva011_without_mathjax(dash_dcc, is_eager):
    app = Dash(__name__, eager_loading=is_eager, assets_folder="../../assets")

    app.layout = html.Div([
        dcc.Graph(
            id="output",
            figure={
                "data": [{
                    "y": [3, 1, 2]
                }],
                "layout": {
                    "title": {
                        "text": "Apple: $2, Orange: $3"
                    }
                },
            },
        )
    ])

    dash_dcc.start_server(app)
    assert dash_dcc.wait_for_element(".gtitle").text == "Apple: $2, Orange: $3"

    assert not dash_dcc.driver.execute_script("return !!window.MathJax")

    assert dash_dcc.get_logs() == []
def update_fig(data, column_option, figure_option):
    if column_option == "Term":
        _df = pd.DataFrame(data).groupby(column_option).agg(
            {"Enrolled": "sum"})
        str_title = "Enrollment per {:s}".format(column_option)
    else:
        _df = pd.DataFrame(data).groupby(column_option).agg(
            {"Enrolled": "mean"})
        str_title = "Average Enrollment per {:s}".format(column_option)

    if figure_option == 'line':
        fig = (px.line(
            _df,
            y=["Enrolled"],
            title=str_title,
        ).update_xaxes(showticklabels=True).update_yaxes(
            rangemode="tozero").update_layout(
                showlegend=False,
                xaxis_type="category",
                yaxis_title="Enrolled",
                barmode="overlay",
            ))
    else:
        fig = (px.bar(
            _df,
            y=["Enrolled"],
            title=str_title,
        ).update_xaxes(showticklabels=True).update_layout(
            showlegend=False,
            xaxis_type="category",
            yaxis_title="Enrolled",
            barmode="overlay",
        ))
    return [dcc.Graph(figure=fig)]
Exemplo n.º 20
0
def test_grva012_with_mathjax(dash_dcc, is_eager):
    app = Dash(__name__, eager_loading=is_eager, assets_folder="../../assets")

    app.layout = html.Div([
        dcc.Graph(
            mathjax=True,
            id="output",
            figure={
                "data": [{
                    "y": [3, 1, 2]
                }],
                "layout": {
                    "title": {
                        "text": "Equation: $E=mc^2$"
                    }
                },
            },
        )
    ])

    dash_dcc.start_server(app)
    dash_dcc.wait_for_element(".gtitle-math")

    assert dash_dcc.driver.execute_script("return !!window.MathJax")

    assert dash_dcc.get_logs() == []
Exemplo n.º 21
0
def test_dvui001_disable_props_check_config(dash_duo):
    app = Dash(__name__)
    app.layout = html.Div(
        [
            html.P(id="tcid", children="Hello Props Check"),
            dcc.Graph(id="broken", animate=3),  # error ignored by disable
        ]
    )

    dash_duo.start_server(
        app,
        debug=True,
        use_reloader=False,
        use_debugger=True,
        dev_tools_hot_reload=False,
        dev_tools_props_check=False,
    )

    dash_duo.wait_for_text_to_equal("#tcid", "Hello Props Check")
    assert dash_duo.find_elements("#broken svg.main-svg"), "graph should be rendered"

    # open the debug menu so we see the "hot reload off" indicator
    dash_duo.find_element(".dash-debug-menu").click()
    sleep(1)  # wait for debug menu opening animation

    dash_duo.percy_snapshot("devtools - disable props check - Graph should render")
Exemplo n.º 22
0
def forecast(n, n_days, val):
    if n == None:
        return [""]
    if val == None:
        raise PreventUpdate
    fig = prediction(val, int(n_days) + 1)
    return [dcc.Graph(figure=fig)]
Exemplo n.º 23
0
 def get_regional_emissions_comparison():
     return html.Div(
         dbc.Col(
             [
                 html.Br(),
                 html.Br(),
                 html.H2(
                     [
                         "Emissions Across Regions in ",
                         html.Strong(
                             id="country_name",
                             style={
                                 "fontWeight": "normal",
                                 "color": "green"
                             },
                         ),
                     ],
                     style={
                         "textAlign": "center",
                         "marginLeft": "12%"
                     },
                 ),
                 dcc.Graph(id="regional_emissions_comparison_choropleth"),
             ],
             id="regional_emissions_comparison_component",
         ),
         style={"marginLeft": "-12%"},
     )
Exemplo n.º 24
0
def display_selected_drive_charts(value):



    filtered_df = auto_data[auto_data['drive-wheels']==value].groupby(['drive-wheels','body-style'],as_index=False). \
             mean()

    filtered_df = filtered_df

    fig1 = px.pie(filtered_df,
                  values='price',
                  names='body-style',
                  title="Pie Chart")
    fig2 = px.bar(filtered_df, x='body-style', y='price', title='Bar Chart')

    return [dcc.Graph(figure=fig1), dcc.Graph(figure=fig2)]
Exemplo n.º 25
0
        def update_graph(figure):
            if figure is None:
                raise PreventUpdate
            elif figure == "error":
                search_error = (MessageContainer(
                    [
                        MessageBody(
                            dcc.Markdown(
                                "Plotting is only available for phase diagrams containing 2-4 components."
                            ))
                    ],
                    kind="warning",
                ), )
                return search_error

            else:
                plot = [
                    dcc.Graph(
                        figure=figure,
                        config={
                            "displayModeBar": False,
                            "displaylogo": False
                        },
                    )
                ]
                return plot
Exemplo n.º 26
0
def test_dveh003_validation_errors_in_place(dash_duo):
    app = Dash(__name__)

    app.layout = html.Div([
        html.Button(id="button", children="update-graph", n_clicks=0),
        dcc.Graph(id="output", figure={"data": [{
            "y": [3, 1, 2]
        }]}),
    ])

    # animate is a bool property
    @app.callback(Output("output", "animate"), [Input("button", "n_clicks")])
    def update_output(n_clicks):
        if n_clicks == 1:
            return n_clicks

    dash_duo.start_server(
        app,
        debug=True,
        use_reloader=False,
        use_debugger=True,
        dev_tools_hot_reload=False,
    )

    dash_duo.wait_for_element(".js-plotly-plot .main-svg")

    dash_duo.find_element("#button").click()
    dash_duo.wait_for_text_to_equal(dash_duo.devtools_error_count_locator, "1")
    dash_duo.percy_snapshot("devtools - validation exception - closed")

    dash_duo.find_element(".test-devtools-error-toggle").click()
    dash_duo.percy_snapshot("devtools - validation exception - open")
Exemplo n.º 27
0
def get_funding_chart_by_orga(iso_code, organization):
    data = fts_api.get_country_funding_for_organization(iso_code, organization)
    if len(data['funding_source']) == 0:
        return ''
    labels = []
    values = []
    for orga in data['funding_source']:
        labels.append(orga['name'])
        values.append(orga['totalFunding'])

    trace = go.Pie(labels=labels,
                   values=values,
                   hole=0.4,
                   hoverinfo='label+value',
                   showlegend=False,
                   textinfo='percent',
                   marker=dict(line=dict(color='#000000', width=2)))
    return dcc.Graph(
        id=organization + '-chart-progress',
        figure={
            'data': [trace],
            'layout':
            go.Layout(title='Who is funding {0} (for Nutrition)'.format(
                organization.upper()))
        })
Exemplo n.º 28
0
 def update_output(n_clicks):
     if n_clicks == 1:
         return dcc.Graph(id="output",
                          animate=0,
                          figure={"data": [{
                              "y": [3, 1, 2]
                          }]})
Exemplo n.º 29
0
def plot(test_passed, show_opt, jsonified_data, y_type, x_type, plot_scale,
         prev_show_opt):
    if test_passed is True:
        # Load and shape the data
        df_x, df_y, to_plot_list, x_tag, y_label = shape_reso_df_to_output(
            x_type=x_type,
            y_type=y_type,
            show_opt=show_opt,
            jsonified_data=jsonified_data,
            prev_show_opt=prev_show_opt,
            to_csv=False)
        df_to_plot = df_y[to_plot_list]
        df_to_plot.insert(loc=0, column=x_tag, value=df_x[x_tag])
        jsonized_plot_df = df_to_plot.to_json(orient='split',
                                              date_format='iso')

        # Plot in matplotlib
        fig = plt.figure()
        ax1 = fig.add_subplot(111)
        try:
            ax1 = df_to_plot.set_index(keys=x_tag).plot(legend=False, ax=ax1)
        except TypeError:
            pass
        ax1.set_ylabel(y_label)

        # Convert to plotly and format layout
        plotly_fig = shape_matplot_to_plotly(fig=fig,
                                             y_type=y_type,
                                             plot_scale=plot_scale)

        return html.Div([
            dcc.Graph(figure=plotly_fig, id=app_id_dict['plot_fig_id'])
        ]), [json.dumps(jsonized_plot_df)]
    else:
        return plot_loading, [None]
Exemplo n.º 30
0
def line_plot(df: DataFrame) -> dcc.Graph:
    """
    Create and return the line plot for a dataframe.

    Parameters
    ----------
    df : DataFrame
        Dataframe to plot.

    Returns
    -------
    g : dcc.Graph
        Dash object containing the line plot.

    Examples
    --------
    Get the `figure` attribute if you want to display this in a Jupyter notebook.
    >>> line_plot = line_plot(timeseries_container.timeseries_data).figure
    >>> line_plot.show()
    """
    fig = go.Figure(
        data=go.Scatter(x=df.index, y=df.iloc[:, 0], mode='lines+markers'))
    fig.update_layout(title=_('Line plot'),
                      xaxis_title=df.index.name,
                      yaxis_title=df.columns[0])

    g = dcc.Graph(figure=fig)
    return g