从破折号样本存储库中在 Plotly 中复制树形图

问题描述 投票:0回答:1

我想从破折号样本存储库中重现 Plotly 中的树形图

示例代码如下:

import pandas as pd
from dash import Dash, Input, Output, callback, dcc, html, State
import plotly.express as px
import dash_bootstrap_components as dbc

df = pd.read_table(
    "https://raw.githubusercontent.com/plotly/datasets/master/global_super_store_orders.tsv"
)

df["profit_derived"] = df["Profit"].str.replace(",", ".").astype("float")
df["ship_date"] = pd.to_datetime(df["Ship Date"])

# Hierarchical charts (sunburst, treemap, etc.) work only with positive aggregate values
# In this step, we ensure that aggregated values will be positive
df = df.query(expr="profit_derived >= 0")

df = df[["profit_derived", "Segment", "Region", "ship_date"]]

app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = dbc.Container(
    [
        html.H4(
            "Distribution of profit as per business segment and region",
            style={"textAlign": "center"},
            className="mb-3",
        ),
        # ------------------------------------------------- #
        # Modal
        html.Div(
            [
                dbc.Button("Open modal", id="open", n_clicks=0),
                dbc.Modal(
                    [
                        dbc.ModalHeader(dbc.ModalTitle("Filters")),
                        dbc.ModalBody(
                            [
                                # Filter within dbc Modal
                                html.Label("Regions"),
                                dcc.Dropdown(
                                    id="dynamic_callback_dropdown_region",
                                    options=[
                                        {"label": x, "value": x}
                                        for x in sorted(df["Region"].unique())
                                    ],
                                    multi=True,
                                ),
                                html.Br(),
                                html.Label("Ship Date"),
                                dcc.DatePickerRange(
                                    id="my-date-picker-range",
                                    min_date_allowed=min(df["ship_date"]),
                                    max_date_allowed=max(df["ship_date"]),
                                    end_date=max(df["ship_date"]),
                                    start_date=min(df["ship_date"]),
                                    clearable=True,
                                ),
                            ]
                        ),
                    ],
                    id="modal",
                    is_open=False,
                ),
            ],
            className="mb-5",
        ),
        # ---------------------------------------- #
        # Tabs
        dcc.Tabs(
            id="tab",
            value="treemap",
            children=[
                dcc.Tab(label="Treemap", value="treemap"),
                dcc.Tab(label="Sunburst", value="sunburst"),
            ],
        ),
        html.Div(id="tabs-content"),
    ],
    fluid=True,
)


@callback(
    Output("tabs-content", "children"),
    Input("dynamic_callback_dropdown_region", "value"),
    Input("tab", "value"),
    Input("my-date-picker-range", "start_date"),
    Input("my-date-picker-range", "end_date"),
)
def main_callback_logic(region, tab, start_date, end_date):
    dff = df.copy()

    if region is not None and len(region) > 0:
        dff = dff.query("Region == @region")

    if start_date is not None:
        dff = dff.query("ship_date > @start_date")

    if end_date is not None:
        dff = dff.query("ship_date < @end_date")

    dff = dff.groupby(by=["Segment", "Region"]).sum().reset_index()

    if tab == "treemap":
        fig = px.treemap(
            dff, path=[px.Constant("all"), "Segment", "Region"], values="profit_derived"
        )
    else:
        fig = px.sunburst(
            dff, path=[px.Constant("all"), "Segment", "Region"], values="profit_derived"
        )

    fig.update_traces(root_color="lightgrey")
    fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))

    return dcc.Graph(figure=fig)


@callback(
    Output("modal", "is_open"),
    Input("open", "n_clicks"),
    State("modal", "is_open"),
)
def toggle_modal(n1, is_open):
    if n1:
        return not is_open
    return is_open


if __name__ == "__main__":
    app.run_server()

但是,当我运行代码时,它无法正确显示示例。

在访问本地主机上的仪表板之前,以下输出将打印到控制台:

Could not infer format, so each element will be parsed individually, falling back to `dateutil`. To ensure parsing is consistent and as-expected, please specify a format.

当我访问本地主机上的仪表板时,附加输出会打印到控制台。

如何正确重现破折号示例?

python plotly plotly-dash
1个回答
0
投票

该代码在 pandas 1.x 中有效,但在 pandas 2.x 中无效。这是因为之前

numeric_only
DataFrameGroupBy.sum
参数以
True
作为默认值,所以非数字类型的列被丢弃。

事实上,这已经在 Pandas 1.5 中生成了 DeprecatedWarning,但在 Pandas 2 中,默认值现在是

False
,并且如果任何列不是数字类型,则直接生成异常,如本例中的列
ship_date

错误在第102行:

dff = dff.groupby(by=["Segment", "Region"]).sum().reset_index()

指定

numeric_only=True
:

dff = dff.groupby(by=["Segment", "Region"]).sum(numeric_only=True).reset_index()

或者仅选择具有数字类型的列:

dff = dff.groupby(by=["Segment", "Region"])["profit_derived"].sum().reset_index()

至于另一个警告,如果你想让它消失,修改第11行:

df["ship_date"] = pd.to_datetime(df["Ship Date"])

df["ship_date"] = pd.to_datetime(df["Ship Date"], format='mixed')

完整代码:

import pandas as pd
from dash import Dash, Input, Output, callback, dcc, html, State
import plotly.express as px
import dash_bootstrap_components as dbc

df = pd.read_table(
    "https://raw.githubusercontent.com/plotly/datasets/master/global_super_store_orders.tsv"
)

df["profit_derived"] = df["Profit"].str.replace(",", ".").astype("float")
df["ship_date"] = pd.to_datetime(df["Ship Date"], format='mixed')

# Hierarchical charts (sunburst, treemap, etc.) work only with positive aggregate values
# In this step, we ensure that aggregated values will be positive
df = df.query(expr="profit_derived >= 0")

df = df[["profit_derived", "Segment", "Region", "ship_date"]]

app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = dbc.Container(
    [
        html.H4(
            "Distribution of profit as per business segment and region",
            style={"textAlign": "center"},
            className="mb-3",
        ),
        # ------------------------------------------------- #
        # Modal
        html.Div(
            [
                dbc.Button("Open modal", id="open", n_clicks=0),
                dbc.Modal(
                    [
                        dbc.ModalHeader(dbc.ModalTitle("Filters")),
                        dbc.ModalBody(
                            [
                                # Filter within dbc Modal
                                html.Label("Regions"),
                                dcc.Dropdown(
                                    id="dynamic_callback_dropdown_region",
                                    options=[
                                        {"label": x, "value": x}
                                        for x in sorted(df["Region"].unique())
                                    ],
                                    multi=True,
                                ),
                                html.Br(),
                                html.Label("Ship Date"),
                                dcc.DatePickerRange(
                                    id="my-date-picker-range",
                                    min_date_allowed=min(df["ship_date"]),
                                    max_date_allowed=max(df["ship_date"]),
                                    end_date=max(df["ship_date"]),
                                    start_date=min(df["ship_date"]),
                                    clearable=True,
                                ),
                            ]
                        ),
                    ],
                    id="modal",
                    is_open=False,
                ),
            ],
            className="mb-5",
        ),
        # ---------------------------------------- #
        # Tabs
        dcc.Tabs(
            id="tab",
            value="treemap",
            children=[
                dcc.Tab(label="Treemap", value="treemap"),
                dcc.Tab(label="Sunburst", value="sunburst"),
            ],
        ),
        html.Div(id="tabs-content"),
    ],
    fluid=True,
)


@callback(
    Output("tabs-content", "children"),
    Input("dynamic_callback_dropdown_region", "value"),
    Input("tab", "value"),
    Input("my-date-picker-range", "start_date"),
    Input("my-date-picker-range", "end_date"),
)
def main_callback_logic(region, tab, start_date, end_date):
    dff = df.copy()

    if region is not None and len(region) > 0:
        dff = dff.query("Region == @region")

    if start_date is not None:
        dff = dff.query("ship_date > @start_date")

    if end_date is not None:
        dff = dff.query("ship_date < @end_date")

    dff = dff.groupby(by=["Segment", "Region"]).sum(numeric_only=True).reset_index()

    if tab == "treemap":
        fig = px.treemap(
            dff, path=[px.Constant("all"), "Segment", "Region"], values="profit_derived"
        )
    else:
        fig = px.sunburst(
            dff, path=[px.Constant("all"), "Segment", "Region"], values="profit_derived"
        )

    fig.update_traces(root_color="lightgrey")
    fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))

    return dcc.Graph(figure=fig)


@callback(
    Output("modal", "is_open"),
    Input("open", "n_clicks"),
    State("modal", "is_open"),
)
def toggle_modal(n1, is_open):
    if n1:
        return not is_open
    return is_open


if __name__ == "__main__":
    app.run_server()
© www.soinside.com 2019 - 2024. All rights reserved.