graph_objs.Layout.update() method not updating annotations properly
When trying to update annotations within plotly.graph_objs.Layout using the .update() method, the annotations do not appear to update properly. This may be related to issue https://github.com/plotly/plotly.js/issues/1010
To clarify, it functions correctly if the len(annotations) is the same. However, if say 1 annotation was in the original layout, but the new layout has 2 annoations, only the first is updated and the second won't appear. Perhaps an internal len(annotations) is being used and not updated?
An example is shown below (I'm using Jupyter):
import plotly
import plotly.graph_objs as go
print(plotly.__version__)
plotly.offline.init_notebook_mode() # run at the start of every ipython notebook
# Create random data with numpy
import numpy as np
N = 50
random_x = np.random.randn(N)
random_y = np.random.randn(N)
# Create a trace
trace = go.Scatter(
x = random_x,
y = random_y,
mode = 'markers'
)
data = [trace]
originalAnnotations=[
go.Annotation(x=.5, y=1, xref='paper',yref='paper', text='First Annotation',showarrow=False,)
]
differentAnnotations=[
go.Annotation(x=.5, y=1, xref='paper',yref='paper', text='New First Annotation',showarrow=False,),
go.Annotation(x=.5, y=.95, xref='paper',yref='paper', text='Second Annotation',showarrow=False,)
]
layout=go.Layout(
yaxis = dict(zeroline = False),
annotations=originalAnnotations,
)
# update the layout with different annotations now.
layout.update(annotations=differentAnnotations)
# where's the second annotation?? doesn't show up in the graph
plotly.offline.iplot({"data": data,"layout": layout})
# let's try it this way
layout['annotations']=differentAnnotations
plotly.offline.iplot({"data": data,"layout": layout})
#success, but layout.update() method broken?
2.0.9


@tahouse Your code is wrong, that is why the update is not performed as you want. These two lines:
layout=go.Layout(
yaxis = dict(zeroline = False),
annotations=originalAnnotations,
)
# update the layout with different annotations now.
layout.update(annotations=differentAnnotations)
do the same as this simple code:
a=2
a=3
The correct way to update the annotations is to concatenate the two lists of annotations:
layout['annotations']+=differentAnnotations
@empet Thanks for the response, and I see your point. Of course you can simply change the dictionary value manually (i.e. not using the update method) like I did at the bottom of my post and you did your solution. By update, I'm referring to replacing the current annotation set (hence the var name differentAnnotations), not an additional set, combining it with whatever already exists. Your solution concatenates and results in three annotations -- not the two I wanted or gave the example of above. That is not an acceptable result.
Beyond that, coding
a=2
a=3
isn't wrong in any way. More analogous would be
a = value0
...code...
a.update(value1)
...more code...
a.update(value2)
You're redefining a variable, which is essential in any programming language, and it depends on the update method working as documented.
Looking back at the title of the issue, "graph_objs.Layout.update() method not updating annotations properly" you gave the same workaround I used in my example code -- by simply not using the update method. The update method should update all of the layout parameters and it currently doesn't. At least that's according to its documentation..
From the help(graph_objs.Layout) result:
| update(self, dict1=None, **dict2)
| Update current dict with dict1 and then dict2.
|
| This recursively updates the structure of the original dictionary-like
| object with the new entries in the second and third objects. This
| allows users to update with large, nested structures.
|
| Note, because the dict2 packs up all the keyword arguments, you can
| specify the changes as a list of keyword agruments.
|
| Examples:
| # update with dict
| obj = Layout(title='my title', xaxis=XAxis(range=[0,1], domain=[0,1]))
| update_dict = dict(title='new title', xaxis=dict(domain=[0,.8]))
| obj.update(update_dict)
| obj
| {'title': 'new title', 'xaxis': {'range': [0,1], 'domain': [0,.8]}}
|
| # update with list of keyword arguments
| obj = Layout(title='my title', xaxis=XAxis(range=[0,1], domain=[0,1]))
| obj.update(title='new title', xaxis=dict(domain=[0,.8]))
| obj
| {'title': 'new title', 'xaxis': {'range': [0,1], 'domain': [0,.8]}}
|
| This 'fully' supports duck-typing in that the call signature is
| identical, however this differs slightly from the normal update
| method provided by Python's dictionaries.
The documentation referenced above says very clearly that the method "updates the structure of the original dictionary-like object with the new entries in the second and third objects" So basically, either the update method is broken, or the documentation is wrong and needs to specify what can and can't be updated with the update method.
Thanks again, and happy to hear any other ideas for the strange behavior.
@tahouse Excuse me, in the process of copying from my notebook and pasting here I've lost the line
layout['annotations']=[]
before:
layout['annotations']+=differentAnnotations
This is just a solution on how to perform the updating from one annotation to two annotations.
The method Layout.update() seems not working in this case.
If you don't define layout as an instance of the class Layout,
but just as a dict:
layout=dict(annotations=[dict(x=.5, y=1, xref='paper',yref='paper',
text='FirstAnnotation',showarrow=False)])
then the usual update of this dict works well:
layout.update(annotations=[dict(x=.5, y=1, xref='paper',yref='paper',
text='New First Annotation',showarrow=False),
dict(x=.5, y=.95, xref='paper',yref='paper',
text='Second Annotation',showarrow=False)])
Thanks for the reply @empet . I like your solution as it allows for an update method as one would expect. I'll apply this in my own code.
I'm keeping the issue open as you've confirmed that Layout.update() seems to not be working as expected. It's only a minor annoyance that can be worked around as you've shown. Nonetheless, it should probably get fixed at some point if users are going to be encouraged to use Plotly's subclassed dictionaries.
Thanks again!
I just noticed also a weird behaviour with update and annotations.
More specifically when updating the layout without annotations it does not add it.
This simple code illustrates what I mean:
>>> import plotly.graph_objs as go
>>> layout=go.Layout(title="First Plot", xaxis={'title':'x1'}, yaxis={'title':'x2'})
>>> layout.update(dict(annotations=[go.layout.Annotation(text="Highest Point", x=3, y=6)]))
>>> layout
Layout({
'title': 'First Plot', 'xaxis': {'title': 'x1'}, 'yaxis': {'title': 'x2'}
})
It seems to be inconsistent with tutorial.
Update: seems that plotly=3.1.1 fixes my problem this.
Hello, I'm on plotly 3.7.1 and ran into this very issue so I believe the update method is still broken, at least in the case of subplots. If I call
fig = tools.make_subplots(rows=n_rows,cols=n_cols, subplot_titles=[titles])
Then the annotations are restricted to the length of the list of subplot_titles and if I call update on the annotations then it only updates as many elements in my new annotations as were originally added to the figure.
Hi all, I was searching a lot for solution for my issue and seems I have problem mentioned in this issue. I am using plotly 4.6.0 and seems updating annotations still does not work. I am trying to plot heatmap with annotations
but can not update annotations when adding additional row/columns.
I have tried different code but no sucess
option1:
x=corr.columns.tolist()
y=corr.columns.tolist()
z = corr.values
annotations = go.Annotations()
for n, row in enumerate(z):
for m, val in enumerate(row):
annotations.append(go.Annotation(text=str(z[n][m]), x=x[m], y=y[n],
xref='x1', yref='y1', showarrow=False))
trace = go.Heatmap(x=x, y=y, z=z, colorscale='rdylbu')
fig = go.Figure(data=go.Data([trace]))
fig.update_layout(
annotations=annotations
)
option2:
corr_text = np.around(corr.values, decimals=2)
font_colors = ['white', 'black']
x = y = corr.columns.tolist()
corr_matrix_fig = ff.create_annotated_heatmap(corr.values, x=x, y=y, annotation_text=corr_text, colorscale='rdylbu',
font_colors=font_colors, showscale = False)
#set xaxis to bottom
corr_matrix_fig['layout']['xaxis']['side'] = 'bottom'