Reduce json file size saved by Plotly in Python

Viewed 139

I am trying to plot a Histogram from a 3D NumPy array with 16 million points with this Python code:

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)

I realized, that Plotly saves all the data points even for histogram and makes it unusable for websites. Is there a way to save a plot with only bin data and do not keep the raw data points in the JSON file? Thanks!

1 Answers

pre-calculated histogram

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)

size analysis

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