'how to recreate plotly fig object from jupyter notebook

I have a jupyter notebook that has a plotly figure object. I want to be able to recreate the plotly fig object from the plot but I only have the output cell containing the plot from a previous run. I can not re-run the notebook to recreate the figure object. How do I extract the figure object from the output cell since all the data is already there.



Solution 1:[1]

first get cells from the current or other notebook.

import nbformat

path =r'c:my_jupyter_notebook.ipynb'

NB_VERSION = 4

with open(path) as f:
    nb = nbformat.read(f, NB_VERSION)

markdown_cells = [
    cell['source']
    for cell in nb['cells']  # go through the cells
    if cell['cell_type'] == 'markdown' and cell['source']  # skip things like 'code' cells, and empty markdown cells
]

out_cells=[]
for cell in nb['cells']:
    if 'outputs' in cell:
        out_cells.append(cell)

next get fig dict from the cell containing your plot. in my case cell index 1 has the plot

out_cells[1]['outputs'][0]['data']['application/vnd.plotly.v1+json'].keys()
d=out_cells[1]['outputs'][0]['data']['application/vnd.plotly.v1+json']
fig_cell_dict={key:value for key,value in d.items() if key != 'config'} # get only data and layout i.e ignore config key

finally convert the dict to fig object

fig=go.Figure (fig_cell_dict)
fig

the fig object has been recreated from a cell containing the plot

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user15420598