vestland
vestland

Reputation: 61164

How to make a copy of a plotly figure object?

How do you copy a plotly figure object in order to make a few changes but keep the same basic structure for other plots?

The following raises an Attribute error:

Code:

fig2=fig1.copy()

Error:

AttributeError: 'Figure' object has no attribute 'copy'

And of course fig2=fig1 will not help because both names will point to the same object.

Upvotes: 5

Views: 4930

Answers (1)

vestland
vestland

Reputation: 61164

Like the error message says, fig1 or go.Figure() does not have a copy functionality or attribute. The solution is easy though; just make another plotly object using go.Figure() directly on your existing fig1:

fig2 = go.Figure(fig1)

Here's an example where you make a copy of fig1 named fig2, and add a title to fig2 only.

Of course this makes a lot more sense for more complex figures.

Code 1:

import plotly.graph_objects as go
animals=['giraffes', 'orangutans', 'monkeys']

fig1 = go.Figure([go.Bar(x=animals, y=[20, 14, 23])])
fig1.show()

Plot 1:

enter image description here

Code 2:

fig2=go.Figure(fig1)
fig2['layout']['title']['text']='Figure2'
fig2.show()

Plot 2:

enter image description here

And just to make sure that fig1 is left alone:

Code 3:

fig1.show()

Plot 3:

enter image description here

Upvotes: 12

Related Questions