You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly Dash中直方图显示空白但Jupyter Notebook正常的问题求助

Plotly Dash中直方图显示空白但Jupyter Notebook正常的问题求助

我正在尝试搭建一个Dash应用,但遇到了个头疼的问题:我想展示的直方图在Jupyter Notebook里显示完全正常,但放到Dash里就变成空白的了。

Jupyter里正常显示的效果是这样的:
Jupyter中正常显示的直方图:每个类别有7个分组条形

下面是我在Notebook里用来生成这个图表的完整代码:

import kagglehub
import pandas as pd
import matplotlib.pyplot as plt
import math
import re
import plotly.graph_objects as go
import plotly.express as px

def get_class(text):
    x = re.findall("\n (\w*) Class: (\w*) \n", text)
    if x :
        return(list(x[0]))
    else:
        return ["None", "None"]
def get_class_type(text):
    return get_class(text)[0]
def get_class_spec(text):
    return get_class(text)[1]
def get_series(scp_code):
    num = int(scp_code[4:])
    return math.ceil(num/1000)

path = kagglehub.dataset_download("czzzzzzz/scp1to7")
df = pd.read_csv(f"{path}/scp6999.csv")
# 我把上面两行换成了本地路径读取,避免反复请求Kaggle数据集
# df = pd.read_csv("<insert path on my machine>/scp6999.csv")

df["class type"] = df["text"].apply(get_class_type)
df["class"] = df["text"].apply(get_class_spec)
df["series"] = df["code"].apply(get_series)

primary_classes=["Safe", "Euclid", "Keter"]
primary_classes_df = df[df["class"].isin(primary_classes)]
class_counts = primary_classes_df.groupby(["class", "series"]).count().reset_index()

fig = px.histogram(class_counts, x="class", y="code", color="series", color_discrete_sequence=px.colors.sequential.Plasma_r, barmode="group",
                  title="Distribution of SCPs by containment class by series")
fig.update_xaxes(categoryorder="array", categoryarray=primary_classes)
fig.update_layout(yaxis_title="")
fig.update_traces(hovertemplate='Total SCPs: %{y}<extra></extra>')
fig.show()

在Dash里,我用了同样的代码,只是把最后一行fig.show()换成了下面的代码:

graph1 = dcc.Graph(
    figure = fig,
    className="border",
)

结果我遇到了这个错误:

ValueError: Cannot accept list of column references or list of columns for both `x` and `y`

于是我尝试把DataFrame列转换成列表变量来传入,修改后的代码是这样的:

x_data = class_counts["class"].tolist()
y_data = class_counts["code"].tolist()
color_data = class_counts["series"].tolist()
fig = px.histogram(class_counts, x=x_data, y=y_data, color=color_data, 
    color_discrete_sequence=px.colors.sequential.Plasma_r, barmode="group",
    title="Distribution of SCPs by containment class by series")

现在错误倒是没有了,但图表变成了完全空白的状态——只有标题和坐标轴,看不到任何条形。我检查过了,class_counts这个DataFrame是正常的,有21行数据,和预期一致。

Dash里的空白图表是这样的:
Dash中显示的空白图表:只有标题和坐标轴,没有条形

我真的很想知道为什么会出现这种情况,以及怎么才能让Dash里的图表和Notebook里的一样正常显示。提前感谢大家的帮助!

备注:内容来源于stack exchange,提问作者AGA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 19:14:33