【问题标题】:Reduce json file size saved by Plotly in Python减少 Plotly 在 Python 中保存的 json 文件大小
【发布时间】:2021-11-30 17:04:07
【问题描述】:

我正在尝试使用以下 Python 代码从具有 1600 万个点的 3D NumPy 数组中绘制直方图:

data = np.random.random((252,252,252)).flatten()

fig = go.Figure()
fig.add_trace(go.Histogram(x=data, nbinsx=100))
fig.write_json(plotly_file)

我意识到,即使是直方图,Plotly 也会保存所有数据点,使其无法用于网站。有没有办法只保存 bin 数据而不将原始数据点保存在 JSON 文件中?谢谢!

【问题讨论】:

    标签: python json plot plotly


    【解决方案1】:

    预先计算的直方图

    h = np.histogram(data, bins=np.arange(-0.005, 1.006, step=0.01))
    fig2 = go.Figure(
        go.Bar(
            customdata=[f"{n:.3f} - {h[1][i+1]:.3f}, {h[0][i]}" for i, n in enumerate(h[1][:-1])],
            x=h[1],
            y=h[0],
            hovertemplate="(%{customdata})<extra></extra>",
        )
    ).update_layout(bargap=0)
    

    尺寸分析

    import pickle
    print(len(pickle.dumps(fig)), len(pickle.dumps(fig2)))
    
    128029628 9731
    

    【讨论】:

    • 我检查了您的解决方案,效果非常好!谢谢!
    猜你喜欢
    • 2020-09-24
    • 2019-02-13
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 2013-06-25
    • 1970-01-01
    相关资源
    最近更新 更多