5

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.

vestland
  • 55,229
  • 37
  • 187
  • 305

1 Answers1

10

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

vestland
  • 55,229
  • 37
  • 187
  • 305
  • 1
    Hey sir, In code2 why to set :: fig2['layout']['title']['text']='Figure2' instead only fig2['title']? – KcH Oct 14 '19 at 11:29
  • @Codenewbie I don't think you can do anything with just `fig2['title']`. Or can you? – vestland Oct 15 '19 at 08:04
  • I was thinking about the title which(only) has to be changed and the rest we just get from fig1 , so Im worried why to using all three.....Am I correct sir? or missing something? – KcH Oct 15 '19 at 08:07
  • I'm sending you an invitation to chat. – vestland Oct 15 '19 at 08:10