我正在创建一个dash应用程序,并使用plotly express绘制图表.我try 使用to_plotly_json()dash componentsgraphs保存到json文件中. 但是对于pie chart图表,得到的错误如下:

Error-1 The first argument to the plotly.graph_objs.layout.Template
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.Template`
Error-1 The first argument to the plotly.graph_objs.layout.Template
constructor must be a dict or

以下是MWE:

import json

import dash_bootstrap_components as dbc
from dash import dcc

import plotly.express as px

import pandas as pd


def generate_pie_charts(df, template) -> list[dict[str, Any]]:
    pie_charts = list()

    for field in df.columns.tolist():
        
        value_count_df = df[field].value_counts().reset_index()        

        cols = value_count_df.columns.tolist()

        name: str = cols[0]
        value: str = cols[1]

        try:
            figure = px.pie(
                data_frame=value_count_df,
                values=value,
                names=name,
                title=f"Pie chart of {field}",
                template=template,
            ).to_plotly_json()

            pie_chart = dcc.Graph(figure=figure).to_plotly_json()
            
            pie_charts.append(pie_chart)
        except Exception as e:
            print(f"Error-1 {e}")
    
    return pie_charts


def perform_exploratory_data_analysis():
    rows = list()

    template = "darkly"

    info = {
        "A": ["a", "a", "b", "b", "c", "a", "a", "b", "b", "c", "a", "a", "b", "b", "c"],
        "B": ["c", "c", "c", "c", "c", "a", "a", "b", "b", "c", "a", "a", "b", "b", "c"],
    }

    df = pd.DataFrame(info)

    try:
        row = dbc.Badge(
            "For Pie Charts", color="info", className="ms-1"
        ).to_plotly_json()

        rows.append(row)

        row = generate_pie_charts(df, template)  

        rows.append(row)

        data = {"contents": rows}

        status = False

        msg = "Error creating EDA graphs."

        file = "eda.json"

        with open(file, "w") as json_file:
            json.dump(data, json_file)
            msg = "EDA graphs created."
            status = True

    except Exception as e:
        print(f"Error-2 {e}")

    result = (status, msg)

    return result


perform_exploratory_data_analysis()

我错过了什么?

推荐答案

您需要显式加载要使用的主题模板:

from dash_bootstrap_templates import load_figure_template

# ... 

def perform_exploratory_data_analysis():
    rows = list()

    template = "darkly"
    load_figure_template(template)

    # ...

Python相关问答推荐

Locust请求中的Python和参数

如何使用Jinja语法在HTML中重定向期间传递变量?

理解Python的二分库:澄清bisect_left的使用

对Numpy函数进行载体化

rame中不兼容的d类型

发生异常:TclMessage命令名称无效.!listbox"

在Python中管理打开对话框

NP.round解算数据后NP.unique

当独立的网络调用不应该互相阻塞时,'

avxspan与pandas period_range

导入...从...混乱

将JSON对象转换为Dataframe

如何在FastAPI中为我上传的json文件提供索引ID?

使用特定值作为引用替换数据框行上的值

无论输入分辨率如何,稳定扩散管道始终输出512 * 512张图像

如何在Gekko中使用分层条件约束

如何在Airflow执行日期中保留日期并将时间转换为00:00

Pandas:将值从一列移动到适当的列

合并Pandas中的数据帧,但处理不存在的列

对列中的数字进行迭代,得到n次重复开始的第一个行号