将plotlyexpress图转换为json

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

我正在使用

plotly express
创建不同的图表。我正在尝试将
graphs
转换为
json
格式以保存在
json
文件中。这样做时,我使用不同的方法遇到错误,如下所示:

Way-1 code gives error as below
Error-2 Object of type ndarray is not JSON serializable

Way-2 code gives error as below
Error-2 Object of type Figure is not JSON serializable

以下是MWE:

import json

import dash_bootstrap_components as dbc
from dash import dcc
from dash_bootstrap_templates import load_figure_template

import plotly.express as px
import plotly.io as pio

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:
            # Way-1
            # 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()

            

            # Way-2
            figure = px.pie(
                data_frame=value_count_df,
                values=value,
                names=name,
                title=f"Pie chart of {field}",
                template=template,
            )

            figure = pio.to_json(figure)
            # figure = pio.to_json(figure).encode()

            pie_chart = dcc.Graph(figure=pio.from_json(figure)).to_plotly_json()
            # pie_chart = dcc.Graph(figure=pio.from_json(figure.decode())).to_plotly_json()


            pie_charts.append(pie_chart)
        except Exception as e:
            print(f"Error-1 {e}")

    print(f"Length {len(pie_charts)}")
    return pie_charts


def perform_exploratory_data_analysis():
    rows = list()

    template = "darkly"

    load_figure_template(template)

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

我缺少什么?

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

您已经接近了 way-2,您需要:

  1. 使用

    go.Figure
    将图形 (
    pio.to_json()
    ) 转换为 JSON 字符串,以便图形数据中使用的 ndarray 和其他 Python 类型正确转换为其 javascript 等效项。

  2. 使用

    json.loads()
    反序列化 JSON 字符串,以便将数字作为标准 JSON 字典,并防止将来调用
    json.dump()
    时进行双重编码(注意。
    pio.from_json()
    将返回
    go.Figure
    ,而
    json.dump()
    则不会)不知道如何序列化)。

代码的相关部分:

# ...

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

# serializable figure dict
fig_dict = json.loads(figure.to_json())

pie_chart = dcc.Graph(figure=fig_dict).to_plotly_json()

# ...
© www.soinside.com 2019 - 2024. All rights reserved.