我正在创建一个
dash
应用程序并使用 plotly express
绘制图表。我尝试使用 dash components
将 graphs
和 json
保存到 to_plotly_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)
# ...