我想复制a treemap in Plotly from a repository of dash samples张.

enter image description here

示例代码如下:

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()

但是,当我运行代码时,它没有正确显示示例.

enter image description here

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

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.

当我访问本地主机上的仪表板时,additional output被打印到控制台.

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

推荐答案

该代码适用于Pandas 1.x,但不适用于Pandas 2.x.这是因为之前的numeric_only参数DataFrameGroupBy.sum的缺省值为True,因此不是数字类型的列将被丢弃.

事实上,这已经在Pandas 1.5中生成了FutureWarning,但在Pandas 2中,缺省值现在是False,如果有任何列不是数字类型,则直接生成异常,如本例中的ship_date列(datetime64dtype).

错误在第102行:

dff = dff.group通过(通过=["Segment", "Region"]).sum().reset_index()

或者,指定numeric_only=True:

dff = dff.group通过(通过=["Segment", "Region"]).sum(numeric_only=True).reset_index()

或仅 Select 具有数字类型的列:

dff = dff.group通过(通过=["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.group通过(通过=["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()

Python相关问答推荐

调试回归无法解决我的问题

按日期和组增量计算总价值

如何在Python中按组应用简单的线性回归?

如果AST请求默认受csref保护,那么在Django中使用@ system_decorator(csref_protect)的目的是什么?

code _tkinter. Tcl错误:窗口路径名称错误.!按钮4"

在Python中为变量的缺失值创建虚拟值

Python Hashicorp Vault库hvac创建新的秘密版本,但从先前版本中删除了密钥

列表上值总和最多为K(以O(log n))的最大元素数

根据在同一数据框中的查找向数据框添加值

Pytest两个具有无限循环和await命令的Deliverc函数

如何根据参数推断对象的返回类型?

图像 pyramid .难以创建所需的合成图像

如何使用表达式将字符串解压缩到Polars DataFrame中的多个列中?

PyQt5,如何使每个对象的 colored颜色 不同?'

Scrapy和Great Expectations(great_expectations)—不合作

如何在Python中获取`Genericums`超级类型?

在代码执行后关闭ChromeDriver窗口

在Admin中显示从ManyToMany通过模型的筛选结果

使用Python异步地持久跟踪用户输入

Beautifulsoup:遍历一个列表,从a到z,并解析数据,以便将其存储在pdf中.